因此,我的文件内容在文件名testing.txt下,如下所示:
Hello this is the file
there are five lines within this file
third last
second last within file
file ends
如何创建一个分析给定文件中每一行的函数,并返回最长文件行中的最短单词。所以在这个文件的情况下,应该返回单词(are),因为它是整个文件中最长行内的最短单词。谢谢您的帮助!我知道我必须使用for循环来检查文件的每一部分,但我确实错过了我的函数中的一些主要部分。我知道如何在文件中显示每一行但我不知道如何分析文件中的每一行并返回一个特定的(最短的单词)。
所以到目前为止我所拥有的是一个读取文件并打印文件中最大行的函数,但我仍然停留在文件中最短的单词上。
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()
答案 0 :(得分:4)
使用max
和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
示例:
>>> print(shortest_word_in_longest_line('testing.txt'))
'are'