Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Writing a function in python that finds the longest word in a text file. The onl

ID: 3723626 • Letter: W

Question

Writing a function in python that finds the longest word in a text file. The only punctuation used is ,.!?;

I want to inclue somewhere a .strip function to strip the text file of these punctuation symbols but am having trouble with it. I am aware of the .strip restrcitions and want to use this function in my code.

def longestWord(filename): maxword = '' with open(filename, 'r') as x: for line in x: linelist line.splitO for word in LineList: if len(word) > maxwordlength: maxwordlength = len (word) maxword word return maxword

Explanation / Answer

# You can do something like this, There are many other ways too, consider using counters from collections module.

CODE:

def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('test.txt'))