简体   繁体   English

如何在一行中的每个单词然后在文件中的每一行之间循环?

[英]how to loop around every word in a line and then every line in a file?

I have a dictonary like 我有像这样的字典

list1={'ab':10,'ba':20,'def':30}. 

Now my input file contains : 现在我的输入文件包含:

ab def 绝对清晰度
ba ab ba ab

I have coded: 我已经编码:

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

Now I want my output file to contain: 现在,我希望输出文件包含:

ab 10 大约10
def 30 防御30
total: 40 合计:40

ba 20 20 20
ab 10 大约10
total: 30 合计:30

Am not able to loop it for each line. 无法为每一行循环它。 How should I do it? 我该怎么办? I tried a few variations using f.readlines(), f.read(), and tried looping once, then twice with them. 我尝试了一些使用f.readlines(),f.read()的变体,并尝试循环一次,然后循环两次。 But I cannot get it right. 但我做对了。

Instead of giving the answer right away, Let me give you a gist of what you ask: 除了立即给出答案外,让我简要介绍您的要求:

To read the whole file: 要读取整个文件:

f = open('myfile','r')
data = f.read()

To loop through each line in the file: 要遍历文件中的每一行:

for line in data:

To loop through each word in the line: 要遍历该行中的每个单词:

    for word in line.split():

Use it wisely to get what you want. 明智地使用它来获取想要的东西。

You need to make 2 loops and not only one: 您需要制作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)   

I have also cleaned a little bit your code to be more readable. 我还清理了一点代码以使其更具可读性。 Also see What is the python "with" statement designed for? 另请参见python“ with”语句的用途是什么? if you want to understand the with block 如果您想了解with

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM