Python @ DjangoSpin

PyPro #33 Longest word(s) in a file

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Longest word(s) in a file in Python

Longest word(s) in a file in Python

Longest word(s) in a file: Write a Python program to extract the longest word(s) out of a file.

Longest word(s) in a file

# Python program to extract longest word(s) from a file.

# contents of read.txt
Donec volutpat rhoncus velit a tincidunt. Duis est ipsum, finibus nec molestie id, finibus eu nisi. Donec sit amet consectetur dolor, vitae vehicula enim.
Nullam quis purus vestibulum, consequat eros eu, placerat justo. Pellentesque tempus commodo ex, eu mattis lectus tempor vitae.
In felis orci, consectetur nec congue in, ullamcorper vel purus. Aliquam euismod erat ut venenatis placerat. Maecenas eget sodales magna, in interdum velit.

## EXPECTED OUTPUT ##
Pellentesque

fileName = input("Please enter name of the file you wish to process: ")		# 'read.txt'

with open(fileName) as fH:
    contents = fH.read()							# reads all of the file
    words = contents.split()							# splits the contents with whitespace as separator

    maximumLength = len(max(words, key = len))				# max() fetches longest word

    for word in words:																# iterate over each word in words
        if len(word) == maximumLength:
            print(word)																# 'Pellentesque'
Try it here.

See also:


Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon