您将如何读取两个或更多文件,并确定文件中最长的文件?
我尝试做这样的事情,但是由于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
您可以这样做,以将最长的单词保留在变量中,然后在最后打印:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句