簡體   English   中英

Python:如何在文本文件中打印最短和最長單詞?

[英]Python: How to print Shortest and Longest word in a text file?

我試圖使我的程序打印出在文本文件中找到的最短和最長的單詞。 假設我輸入“ Pie is Delicious”作為我的文本塊。 然后,我自己在一行上鍵入EOF以結束輸入階段。 我輸入選項1來看到最短單詞和“ 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))

您沒有將文本拆分為單詞; 相反,您是一個接一個地循環顯示字符。

使用str.split()方法拆分文本,將參數保留為默認值(拆分可變寬度的空白):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM