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.

Respuesta :

Answer:

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.")

Ver imagen sandlee09