如何比较两个文件并查找之间的最佳单词

时间:2016-04-03 22:39:15

标签: python arguments compare

您如何阅读两个或更多文件,并确定文件中最长的文件?

我尝试过这样的事情,但由于for循环,它会打印每个文件中最长的单词。如何比较两个文件并只打印一个输出?

for word in filenames: 
    with open(word) as w:
        x = w.read()   
        y = max(x.split(), key = len) 
    if word >  y: 
        print '\nLongest Word:', y
    else: 
        pass 

1 个答案:

答案 0 :(得分:1)

你可以这样做,在变量中保留最长的单词,然后在结尾打印:

longest_word = ''
for word in filenames: 
    with open(word) as w:
        x = w.read()   
        y = max(x.split(), key = len) 
    if len(y) > len(longest_word):
        longest_word = y 
print '\nLongest Word:', longest_word