In: Computer Science
Write a Python program that reads a file, input by the user, containing one word/token per line with an empty line between sentences. The program prints out the longest word found in the file along with its length.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
#main method
def main():
#reading name of file from user, make sure
that file exists on the
#same directory
filename=input('Enter filename:
')
#opening file to read
file=open(filename)
#initializing a variable to store the
longest word to None
longest_word=None
#looping through each line
(word)
for line
in file:
#removing trailing
newline character from line
line=line.strip()
#checking if line is
not blank
if
len(line)>0:
#if longest_word is not initialized or current word has
more
#length than longest_word, updating longest_word
if longest_word is None or
len(line)>len(longest_word):
longest_word=line
#closing file
file.close()
#printing longest_word if it is not
None
if longest_word is
not None:
print('The
longest word is',longest_word)
#also printing the
length
print('Length of longest word
is',len(longest_word))
#invoking main()
main()
#output (here months.txt contain names of all months in separate lines)
Enter filename: months.txt
The longest word is September
Length of longest word is 9