72.6k views
0 votes
Write a python program that will find the longest word in a file. The program should print the word and the number of characters in that word. Hint you would be using dictionaries, string module, and files for this exercise.

User Eljas
by
4.4k points

1 Answer

5 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It is a function that takes in the file location as a parameter and reads it. It then splits the text into a list and loops through the list. The length of every element is compared to the value in the variable length and if it is larger it saves that words length to the variable length and saves the word to the variable longestWord. These variables get printed at the end of the program. A test case has been provided and can be seen in the image below.

import re

def longestWordInFile(file):

file = open(file, 'r')

text = file.read()

wordList = text.lower()

wordList = re.split('\s', wordList)

length = 0

longestWord = ''

for word in wordList:

if len(word) > length:

length = len(word)

longestWord = word

print(longestWord + " is the longest with " + str(length) + " characters.")

Write a python program that will find the longest word in a file. The program should-example-1
User Sinelaw
by
4.6k points