Reputation: 37
So, my file contents are under file name testing.txt and are as follows:
Hello this is the file
there are five lines within this file
third last
second last within file
file ends
How can i create a function that analyzes each line within the given file and returns the shortest word within the longest file line. So in this files case the word (are) should be returned because it is the shortest word within the longest line in the entire file. Thank you for your help! I know that i have to use a for loop to check each piece of the file but i'm definitely missing some major parts within my function. I know how to display each line within the file but i don't know how to analyze each piece within the file and return a specific one (shortest word).
So what i have so far is a function that reads the file and prints the largest line within the file but i am still stuck on the shortest word within the file.
def main():
List = []
infile = open('testing.txt', 'r')
line1= infile.readline()
line2= infile.readline()
line3= infile.readline()
line4= infile.readline()
line5= infile.readline()
if line1>line2 and line3 and line4 and line5:
List.append(line1)
elif line2>line1 and line3 and line4 and line5:
List.append(line2)
elif line3> line1 and line2 and line4 and line5:
List.append(line3)
elif line4> line1 and line2 and line3 and line5:
List.append(line4)
else:
List.append(line5)
print (List)
main()
Upvotes: 0
Views: 147
Reputation: 20339
Try this for your expected output using max
and min
.
def shortest_word_in_longest_line(filename):
with open(filename) as file:
longest_line = max(file, key=len) # file is an iterator over lines
return min(longest_line.split(), key=len) # whitespace-separated words
Example:
>>> print(shortest_word_in_longest_line('testing.txt'))
'are'
Upvotes: 4