Skip to content Skip to sidebar Skip to footer

Replacing Exact Numbers With Words From Dict Python

I've looked through various examples on here but I can't figure out what is happening. Any help is appreciated. I have a text file from which I want to translate the numbers into w

Solution 1:

First we'll build a dictionary from dictfile, then we'll apply that dictionary to txtfile

withopen('dict.txt') as f:
    d = {a: b for line in f for a,b in line.split()}

withopen('outfile.txt') asout, open('infile.txt') as infile:
    for line in infile:
        line = line.split()
        line = [d[word] if word in d else word for word in line]
        out.write(' '.join(line))

Your big problem was not using split properly. I haven't tested this code, so it may need some tweaking depending on exactly how the files are formatted.

Post a Comment for "Replacing Exact Numbers With Words From Dict Python"