brazjul
brazjul

Reputation: 339

How to Compare two Files and Find the Lasgest Word between

How would you read over two or more files, and determine the longest in a file?

I tried doing something like this, but because of the for loop it will print the longest word in each file. How I can compare both files and print only one output?

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 

Upvotes: 1

Views: 50

Answers (1)

Paulo Almeida
Paulo Almeida

Reputation: 8061

You can do this, to keep the longest word in a variable and then print it at the end:

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

Upvotes: 1

Related Questions