我有像dictonary一样的dictonary
list1={'ab':10,'ba':20,'def':30}.
现在我的输入文件包含:
ab def
ba ab
我编码:
filename=raw_input("enter file:")
f=open(filename,'r')
ff=open(filename+'_value','w')
for word in f.read().split():
s=0
if word in list1:
ff.write(word+'\t'+list1[word]+'\n');
s+=int(list1[word])
else:
ff.write(word+'\n')
ff.write("\n"+"total:%d"%(s)+"\n")
现在我希望我的输出文件包含:
ab 10
def 30
总计:40
ba 20
ab 10
总计:30
无法为每一行循环播放。我该怎么办?我使用f.readlines(),f.read()尝试了一些变体,并尝试循环一次,然后两次使用它们。但我无法做到对。
答案 0 :(得分:2)
不要立即给出答案,让我告诉你一个问题的要点:
阅读整个文件:
f = open('myfile','r')
data = f.read()
循环遍历文件中的每一行:
for line in data:
循环显示行中的每个单词:
for word in line.split():
明智地使用它来获得你想要的东西。
答案 1 :(得分:1)
你需要制作2个循环而不仅仅是一个:
filename = raw_input("enter file:")
with open(filename, 'r') as f, open(filename + '_value','w') as ff:
# Read each line sequentially
for line in f.read():
# In each line, read each word
total = 0
for word in line.split():
if word in list1:
ff.write("%s\t%s\n" % (word, list1[word]))
total += int(list1[word])
else:
ff.write(word+'\n')
ff.write("\ntotal: %s\n" % total)
我还清理了一些代码,使其更具可读性。如果您想了解with
块
答案 2 :(得分:1)
with open("in.txt","r") as f:
with open("out.txt","w") as f1:
for line in f:
words = line.split() # split into list of two words
f1.write("{} {}\n".format((words[0]),list1[words[0]])) # write first word plus value
f1.write("{} {}\n".format((words[1]),list1[words[1]])) # second word plus value
f1.write("Total: {}\n".format((int(list1[words[0]]) + int(list1[words[1]])))) # finally add first and second and get total