我正在尝试编写一个程序,它将读取一个单词文件,并打印出最长单词的长度和该长度的单词。
我已经发现在我的文件中有3个包括标点符号的13字母单词,但我需要程序自己找到最长的单词长度。
这是我的程序:
我已经发现在我的文件中有3个包括标点符号的13字母单词,但我需要程序自己找到最长的单词长度。
这是我的程序:
def main():
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.")
linenum += 1
print(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
我需要输入一个字符函数吗?程序如何找到最长的13个字符单词。
for ...; max -> 13; for ... if (len(word) = max)
- Marc B