Reputation: 13
Problem:
I'm a beginner (3 months) at Python programming, my school assignment asks me to take a text-file with numeric words (e.g.: three oh five nine ...) and convert this to phone numbers (see list below) in a separate file. I've been thinking my brain off and can't find a simple, beginner-friendly style to write a code for this. I would appreciate some help.
My IPO plan is as follows:
Input: Open the text-file in read mode.
Processing: Split the text-file into words in a list. Convert each word to its corresponding number. Display each number in a string.
Output: Print the string containing the phone number.
I can't seem to convert my plan into a code.
The Input is a file which looks as follows:
*EDIT: The problem has been solved and this is the final (working) code:
di = {"oh":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
c=""
infile=open("digit_words.txt","r")
outfile=open("digit_strings.txt","w")
l=infile.readlines()
for line in l:
words=line.split()
for nos in words:
c+=str(di[nos])
print(c, file=outfile)
print("\n")
c=""
infile.close()
outfile.close()}
The matching output is another file that looks as follows:
Upvotes: 1
Views: 385
Reputation: 1130
# pip install word2number
from word2number import w2n
print w2n.word_to_num("two million three thousand nine hundred and eighty four")
# 2003984
Improving the library to a custom number can be using this
word2number.w2n.american_number_system
{'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90, 'hundred': 100, 'thousand': 1000, 'million': 1000000, 'billion': 1000000000, 'point': '.'}
word2number.w2n.american_number_system['oh']=0
word_to_num('oh') # 0 (zero)
Upvotes: -2
Reputation:
Ok, let's change your plan to code. Let's assume that the file name is phno.txt, your code would be:
di= {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
c=""
f=open("phno.txt","r")
l=f.readlines()
for line in l:
words=line.split()
for nos in words:
c+=str(di[nos])
print(c)
print("\n")
c=""
Upvotes: 0