@lakshayarora7/

Longest word(s) in a file

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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.

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'
            
# If you are trying this on an online interpreter such as repl.it, you will have to create the file first using the open() function, and fill it with some sample lines, such as below. Uncomment the following block and place it at the beginning of the script.
#fH2 = open('read.txt', 'w')
#fH2.write('Donec volutpat rhoncus velit a tincidunt. Duis est ipsum, finibus nec molestie id, finibus eu nisi. Donec sit amet consectetur dolor, vitae vehicula enim.\n')
#fH2.write('Nullam quis purus vestibulum, consequat eros eu, placerat justo. Pellentesque tempus commodo ex, eu mattis lectus tempor vitae.\n')
#fH2.write('In felis orci, consectetur nec congue in, ullamcorper vel purus. Aliquam euismod erat ut venenatis placerat. Maecenas eget sodales magna, in interdum velit.')
#fH2.close()