Search code examples
pythonnumbers

How do I convert numeric words to a phone numbers beginner style?


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:

  • two three seven oh nine eight oh
  • eight one eight four three seven two nine six three
  • one five oh three four seven seven two five seven two
  • two nine six two three five oh
  • five two oh four four seven nine eight two one
  • one eight oh oh five five five one two one two
  • four three seven two nine six three

*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:

  • 2370980
  • 8184372963
  • 15034772572
  • 2962350
  • 5204479821
  • 18005551212
  • 4372963

Solution

  • 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=""