Skip to main content
 首页 » 编程设计

python之打印最长单词的长度时出错

2024年10月24日11lautakyan007

我正在编写一个函数,该函数应该打印出文本文件中最大的 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 

请您参考如下方法:

那是因为你没有打印 word 的长度,而是打印了 longest 变量的长度,它指向最后一行中最长的单词(不是文件中真正最长的单词),在特定示例中 - 'unscrambled' ,因此长度为 11。

您应该打印单词的长度。示例 -

with open(filename) as f: 
    for word in real_longest: 
        print("This word is one of the largest:", word) 
        print(len(word))       # <---------- changed here from `len(longest)` .