Python Program to Find the Longest Words in a File

In this example, we will write a python program to find the longest words in a file. To better understand this example, make sure you have knowledge of the following tutorials:-

Python Program to Find the Longest Words in a File

Let us assume we have an about.txt file that contains the following paragraph.

A quick brown fox jumps over the lazy dog
def longest_words(filename):
    with open(filename, 'r') as infile:
        words = infile.read().split()
    max_len = len(max(words, key=len))
    return [word for word in words if len(word) == max_len]

print(longest_words('about.txt'))

The output of the above program is:-

[‘quick’, ‘brown’, ‘jumps’]

SHARE Python Program to Find the Longest Words in a File

You may also like...

1 Response

  1. Mike Jake says:

    how do you make sure it is all letters though?

Leave a Reply

Your email address will not be published.

Share