【发布时间】:2015-10-26 20:38:30
【问题描述】:
我正在编写一个函数,该函数应该打印出文本文件中最大的 3 个单词。一旦这 3 个单词被打印出来,我应该创建一个函数来说明这些单词中有多少个字符。三个最大的单词是 13 个字符,但由于某种原因,我的程序说它们是 11 个字符。
这是我的程序:
def main():
real_longest = ['']
filename = input("What is the filename?")
with open(filename) as f:
linenum = 1
for line in f:
words = line.split()
longest = ''
for word in words:
if len(longest) < len(word):
longest = word
print("Line", linenum, "has", longest, "as the longest word.")
if len(longest) > len(real_longest[0]):
real_longest = [longest]
elif len(longest) == len(real_longest[0]):
real_longest.append(longest)
linenum += 1
print(longest)
with open(filename) as f:
for word in real_longest:
print("This word is one of the largest:", word)
print(len(longest))
main()
这是它返回的内容:
What is the filename?test.txt
Line 1 has Working as the longest word.
Working
Line 2 has possibilities as the longest word.
possibilities
Line 3 has scrambled as the longest word.
scrambled
Line 4 has letters. as the longest word.
letters.
Line 5 has as the longest word.
Line 6 has difficulties as the longest word.
difficulties
Line 7 has permutations. as the longest word.
permutations.
Line 8 has signature as the longest word.
signature
Line 9 has permutations. as the longest word.
permutations.
Line 10 has unscrambled as the longest word.
unscrambled
This word is one of the largest: possibilities
11
This word is one of the largest: permutations.
11
This word is one of the largest: permutations.
11
【问题讨论】:
标签: python