0

テキスト ファイルで見つかった最短の単語と最長の単語をプログラムに出力させようとしています。テキストのブロックとして「パイはおいしい」と入力したとしましょう。次に、EOF を行に単独で入力して、入力フェーズを終了します。最短の単語を確認するためにオプション 1 を入力すると、「is」がポップアップするはずですが、出力として文字「p」しか取得できません。最長の単語を見つけるという 2 番目のオプションでも同じ結果が得られます。「おいしい」はずの文字「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

テキストを単語に分割していません。代わりに、文字を 1 つずつループしています。

str.split()メソッドを使用してテキストを分割し、引数をデフォルトのままにします (可変幅の空白で分割します)。

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