打印最长字的长度时出错?

时间:2015-10-26 20:38:31

标签: python

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

1 个答案:

答案 0 :(得分:2)

那是因为你没有打印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)` .