Ghauri
Ghauri

Reputation: 21

Convert character to number in python

I have a text file which has the following contents such

ABC
AAD
ABE

Where A=5, B=1, C=31, D=101 and E=4. Expected output should be

5,1,31
5,5,101
5,1,4

The problem is only the last line of the text file is being converted to number. Here is what I have tried so far;

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

with open('input.txt') as f:
    content = f.readlines()

for i,j in enumerate(content):
  my_text = content[i]
  new_text = ','.join([my_text[i] for i in range(1, len(my_text), 1)])

reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}
txt = replace_all(new_text, reps)
with open('results.txt', 'a') as my_new_file: 
  my_new_file.write(txt)

What am I doing wrong?

Upvotes: 0

Views: 142

Answers (4)

slightlynybbled
slightlynybbled

Reputation: 2645

Couldn't help myself:

# create a lookup table
lookup = {
    'A': '5',
    'B': '1',
    'C': '31',
    'D': '101',
    'E': '4'
}

# open the input file and the output file
with open('input.txt', 'r') as f, open('results.txt', 'w') as f_new:
    # for each line...
    for line in f.readlines():
        # ...construct a new line...
        nums = [lookup[character] for character in line.strip()]
        newline = ','.join(nums) + '\n'

        # ... and save the new line to the result file
        f_new.write(newline)

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71461

You can try this using list comprehension:

f = open('input.txt').readlines()

f = [i.strip('\n') for i in f]
reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}

new_list = [[reps[b] for b in i] for i in f]

new_file = open('results.txt', 'a')

for i in new_list:
   new_file.write(','.join(i))
   new_file.write('\n')
new_file.close()

Upvotes: 0

chepner
chepner

Reputation: 531808

You can write the whole thing much more simply as

reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}

with open('input.txt') as f, open('results.txt', 'w') as new_file:
    for line in f:
        new_text = ",".join(reps.get(char, char) for char in line)
        new_file.write(new_text)

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81654

Your code only takes into account the value of new_text in the last iteration, which is the last line.

You should move all the logic inside the for loop.

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

with open('input.txt') as f:
    content = f.readlines()

reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}

with open('results.txt', 'a') as my_new_file: 
    for i,j in enumerate(content):
        my_text = content[i]
        new_text = ','.join([my_text[i] for i in range(1, len(my_text), 1)])

        txt = replace_all(new_text, reps)
        my_new_file.write(txt)

Upvotes: 0

Related Questions