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 maxwordExplanation / 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'))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.