0

我试图让我的程序打印出在文本文件中找到的最短和最长的单词。假设我输入“派很美味”作为我的文本块。然后我单独在一行上键入 EOF 以结束输入阶段。我输入了选项 1 来查看 Shortest word,应该会弹出“is”,但我只得到字母“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))
4

1 回答 1

1

您没有将文本拆分为单词;相反,您正在一个接一个地遍历字符。

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

print(min(textInput.split(), key = len))
于 2013-07-14T22:27:22.450 回答