2013-07-14 79 views
0

我試圖讓我的程序打印出在文本文件中找到的最短和最長的單詞。假設我輸入「Pie is delicious」作爲我的文本塊。然後我自己在一行上鍵入EOF以結束輸入階段。我在選項1中輸入以查看最短的單詞並彈出「is」,但我只將字母「p」作爲輸出。對於第二種選擇,我得到了同樣的結果,即找到最長的單詞,當它應該是「美味」時,我最終得到字母「p」。順便說一下,我正在使用min和max函數來完成此操作。Python:如何在文本文件中打印最短和最長的單詞?

#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

您不會將文本拆分爲單詞;相反,你正在一個接一個地循環播放這些字符。

分割文本使用str.split() method離開參數爲默認(可變寬度的空白分裂):

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

哇...這就是它?非常感謝! – user2581724

相關問題