如何打印最长的单词及其长度?

时间:2015-10-26 14:47:29

标签: python

我正在尝试编写一个程序来读取单词文件,并打印最长单词的长度和该长度的单词。

我发现我的文件中有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个字符。

4 个答案:

答案 0 :(得分:3)

列表理解:

<强> lorem.py

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a
type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software
like Aldus PageMaker including versions of Lorem Ipsum.

<强> long.py

def main():
    X=5
    print "Printing top "+str(X)+" longest words:"
    filename = "lorem.txt"
    # Can't get this under 80 characters:
    words = [(linenum, word) for linenum, line in enumerate(open(filename)) for word in line.split()]   
    words = sorted(words,key = lambda x: len(x[1]), reverse=True) #Sort by string length in reverse
    for word in words[:X]:
        print "The longest word '",word[1],"'is on line ",str(word[0])

if __name__ == "__main__":
    main()

<强>输出

>>>
Printing top 5 longest words:
The longest word ' typesetting, 'is on line  5
The longest word ' popularised 'is on line  6
The longest word ' essentially 'is on line  5
The longest word ' typesetting 'is on line  0

您可以通过调整变量来检索前X个字。

如果您不需要行号,这会更简单:

<强> long_no_linenum.py

def main():
    X=5
    print "Printing top " + str(X) + " longest words:"
    filename = "lorem.txt"
    words = (word for word in open(filename).read().split())
    words = sorted(words, key=len, reverse=True)   
    print [word for word in words[:X]]
if __name__ == "__main__":
    main()

没有行号的输出

>>> 
Printing top 5 longest words:
['typesetting,', 'typesetting', 'essentially', 'popularised', "industry's"]

答案 1 :(得分:1)

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 word[-1].isalpha() == False:
                word = word[:-1]
            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)
for word in real_longest:
    print('This word is one of the largest:', word)

答案 2 :(得分:0)

你可以找到带有len(字符串)的字符串的长度,然后你可以保留另一个变量来保存你看过那个长度的单词的次数,当你找到一个新单词时你会重置它最长的词。

答案 3 :(得分:0)

在检查长度之前,您必须从单词中替换特殊字符。要从字符串中替换特殊字符,您可以使用[^ A-Za-z]字母过滤器。

相关问题