【问题标题】:Error printing the length of the longest word?打印最长单词的长度时出错?
【发布时间】: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


    【解决方案1】:

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

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

    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)` .
    

    【讨论】:

    • 这么简单的错误!感谢您的澄清,这行得通!
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2021-04-05
    • 2016-06-14
    • 2016-08-30
    相关资源
    最近更新 更多