• Uncategorized

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?


Warning: Undefined array key 0 in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/single.php on line 9

Warning: Attempt to read property "cat_name" on null in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/single.php on line 9

Warning: Undefined array key 0 in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/single.php on line 14

Warning: Attempt to read property "category_parent" on null in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/functions.php on line 37

Warning: Undefined array key 0 in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/single.php on line 15

Warning: Attempt to read property "category_parent" on null in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/single.php on line 15
Share