在python中将字符转换为数字

时间:2017-05-12 13:39:33

标签: python file

我有一个文本文件,其中包含以下内容

ABC
AAD
ABE

A=5B=1C=31D=101E=4。 预期的输出应该是

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

问题是只将文本文件的最后一行转换为数字。 这是我到目前为止所尝试的内容;

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)

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您的代码仅考虑最后一次迭代中new_text的值,即最后一行。

你应该移动for循环中的所有逻辑。

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)

答案 1 :(得分:0)

无法帮助自己:

# 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)