Python:如何在文本文件中打印最短和最长的单词?

时间:2013-07-14 22:25:14

标签: python file input word shortest

我正在尝试让我的程序打印出文本文件中找到的最短和最长的单词。假设我输入“Pie is delicious”作为我的文本块。然后我自己在一行上键入EOF以结束输入阶段。我输入选项1来查看最短的单词并且弹出“是”,但我只输出字母“p”作为输出。我得到了第二个选项的相同结果,即找到最长的单词,当它应该是“美味”时,我最终得到字母“p”。我正在使用min和max函数来执行此操作。

#Prompt the user to enter a block of text.
done = False
textInput = ""
while(done == False):
    nextInput= input()
    if nextInput== "EOF":
        break
    else:
        textInput += nextInput

#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
    "\n1. shortest word"
    "\n2. longest word"
    "\n3. most common word"
    "\n4. left-column secret message!"
    "\n5. fifth-words secret message!"
    "\n6. word count"
    "\n7. quit")

#Set option to 0.
option = 0

#Use the 'while' to keep looping until the user types in Option 7.
while option !=7:
    option = int(input())

    #Print out the shortest word found in the text.
    if option == 1:
        print(min(textInput, key = len))

    #Print out the longest word found in the text.
    elif option == 2:
        print(max(textInput, key = len))

1 个答案:

答案 0 :(得分:1)

你没有将文字分成单词;相反,你将逐个循环遍历这些角色。

使用str.split() method拆分文本,将参数保留为默认值(在可变宽度空白处拆分):

print(min(textInput.split(), key = len))