在python中将字符转换为数字
我有一个文本文件,其中包含以下内容:在python中将字符转换为数字,python,file,Python,File,我有一个文本文件,其中包含以下内容: ABC AAD ABE 其中A=5,B=1,C=31,D=101,E=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('inp
ABC
AAD
ABE
其中A=5,B=1,C=31,D=101,E=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)
我做错了什么?您的代码只考虑上一次迭代中新文本的值,这是最后一行 您应该在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)
你可以把整件事写得更简单
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)
您可以尝试使用列表理解:
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()
我忍不住:
# 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)
在for中的每次迭代中替换新的_文本,而不保存以前的值。您也不会查看范围中每行的第一个字符,它应该从0Ah开始。我真傻。非常感谢。