Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何比较两个文件并找到其中最短的单词_Python_Arguments_Compare - Fatal编程技术网

Python 如何比较两个文件并找到其中最短的单词

Python 如何比较两个文件并找到其中最短的单词,python,arguments,compare,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 els

如何读取两个或多个文件,并确定文件中最长的文件

我尝试过这样做,但由于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

我试过了,但我得到了这个错误:
y=max(x.split(),key=len)
TypeError:“str”对象不可调用
我选择了一个可怕的变量。。。我正在用一个工作的编辑,没问题。我刚刚重新命名了变量,它起作用了。非常感谢。