Reputation: 71
I'm attempting to write a function that looks through a text file line by line, which contains strings such as "2 plus 6 = 8". I want this program to go through the text file and if it finds an integer, it changes it to the spelled out name of the integer.
So in this example, it opens the file, reads it, sees 2 plus 6 = 8 and changes it to two plus six = eight.
Could someone help me out?
Thanks
Upvotes: 2
Views: 144
Reputation: 54213
This will be hard if you have any numbers beyond 9
, but if not...
from_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
to = ['zero','one','two','three','four','five','six','seven','eight','nine']
table = str.maketrans(dict( zip(from_, to) ))
line = "2 plus 6 = 8"
output = line.translate(table)
# output == "two plus six = eight"
You can build it to look at files by doing:
def spellnumbers(line):
from_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
to = ['zero','one','two','three','four','five','six','seven','eight','nine']
table = str.maketrans( dict(zip(from_, to)) )
return line.translate(table)
with open('path/to/input/file.txt') as inf and open('path/to/output/file.txt', 'w') as outf:
for line in inf:
outf.write(spellnumbers(line))
outf.write('\n')
This basically just builds a dictionary of the form:
{ "0": "zero", "1": "one", ... , "9": "nine" }
Then builds a translation table from it and runs your string through the translation.
If you DO have numbers beyond 9
, then you're going to run into the problem that "10 + 2 = 12"
becomes "onezero + two = onetwo"
This problem is nontrivial.
I happened to see your repost mentioned you're not allowed to use "tables or dictionaries," which is kind of a silly requirement but okay. If that's true, then this must be an assignment for school in which case I won't do your homework for you but perhaps guide you in the right direction:
def spellnumbers(line):
# 1. split the line into words. Remember str.split
# 2. create an empty string that you can write output to. We'll
# use that more in a minute.
# 3. iterate through those words with a for loop and check if
# word == '1':, elif word == '2'; elif word == '3', etc
# 4. for each if block, add the number's name ("one", "two") to
# the output string we created in step 2
# 5. you'll want an else block that just writes the word to
# the output string
# 6. return the output string
f = open('path/to/file.txt')
lines = f.readlines() # this is ugly, but you're a beginner so we'll stick with this
for line in lines:
stripped_line = line.strip() # removes leading and trailing whitespace e.g. \n
print(spellnumbers(line))
# are you printing the output? How are you displaying it?
Upvotes: 2