1

テキスト ファイルで最も多く表示される単語をプログラムに報告させようとしています。たとえば、「こんにちは、私はパイがとても美味しいので好きです」と入力すると、プログラムは「一番好きな出来事」を出力するはずです。オプション 3 を実行すると、次のエラーが表示されます: KeyError: 'h'

#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())

#The error occurs in this specific section of the code.
#If the user selects Option 3,
    elif option == 3:
        word_counter = {}
        for word in textInput:
            if word in textInput:
                word_counter[word] += 1
            else:
                word_counter[word] = 1

        print("The word that showed up the most was: ", word)
4

5 に答える 5

2

私はあなたがやりたいと思うかもしれません:

for word in textInput.split():
  ...

現在、 のすべての文字を反復処理しているだけですtextInput。したがって、すべての単語を反復するには、まず文字列を単語の配列に分割する必要があります。デフォルト.split()では空白で分割されますが、区切り文字を に渡すだけでこれを変更できますsplit()


また、単語が元の文字列ではなく、辞書にあるかどうかを確認する必要があります。だから試してください:

if word in word_counter:
  ...

次に、出現率が最も高いエントリを見つけるには、次のようにします。

highest_word = ""
highest_value = 0

for k,v in word_counter.items():
  if v > highest_value:
    highest_value = v
    highest_word = k

次に、 と の値を出力しhighest_wordますhighest_value


同点を追跡するには、最上位の単語のリストを保持するだけです。より高いオカレンスが見つかった場合は、リストをクリアして再構築を続けます。これまでの完全なプログラムは次のとおりです。

textInput = "He likes eating because he likes eating"
word_counter = {}
for word in textInput.split():
  if word in word_counter:
    word_counter[word] += 1
  else:
    word_counter[word] = 1


highest_words = []
highest_value = 0

for k,v in word_counter.items():
  # if we find a new value, create a new list,
  # add the entry and update the highest value
  if v > highest_value:
    highest_words = []
    highest_words.append(k)
    highest_value = v
  # else if the value is the same, add it
  elif v == highest_value:
    highest_words.append(k)

# print out the highest words
for word in highest_words:
  print word
于 2013-07-14T23:58:57.607 に答える
2

独自のカウンターをローリングする代わりに、コレクション モジュールでカウンターを使用することをお勧めします。

>>> input = 'blah and stuff and things and stuff'
>>> from collections import Counter
>>> c = Counter(input.split())
>>> c.most_common()
[('and', 3), ('stuff', 2), ('things', 1), ('blah', 1)]

また、一般的なコード スタイルとして、次のようなコメントを追加することは避けてください。

#Set option to 0.
option = 0

コードが読みにくくなりますが、読みにくくなります。

于 2013-07-15T01:40:02.557 に答える
1

元の答えは確かに正しいですが、「最初の同点」は表示されないことに注意してください。みたいな文

A life in the present is a present itself.

'a' または 'present' のいずれかのみがナンバーワン ヒットであることを明らかにします。実際、辞書は (一般に) 順序付けされていないため、表示される結果は、複数回繰り返される最初の単語でさえない場合があります。

複数について報告する必要がある場合は、次のことをお勧めします。

1) 「単語」:「ヒット」のキーと値のペアの現在の方法を使用します。
2) 「ヒット数」の最大値を決定します。
3) 最大ヒット数に等しい値の数を確認し、それらのキーをリストに追加します。
4) リストを反復して、ヒット数が最大の単語を表示します。

例:

greatestNumber = 0
# establish the highest number for wordCounter.values()
for hits in wordCounter.values():
    if hits > greatestNumber:
        greatestNumber = hits

topWords = []
#find the keys that are paired to that value and add them to a list
#we COULD just print them as we iterate, but I would argue that this
#makes this function do too much
for word in wordCounter.keys():
    if wordCounter[word] == greatestNumber:
        topWords.append(word)

#now reveal the results
print "The words that showed up the most, with %d hits:" % greatestNumber
for word in topWords:
    print word

Python 2.7 または Python 3 に応じて、マイレージ (および構文) が異なる場合があります。しかし、理想的には - 私見 - 最初にヒットの最大数を決定してから、戻って関連するエントリを新しいリストに追加する必要があります。

編集-別の回答で提案されているように、おそらくカウンターモジュールを使用する必要があります。それが Python がやろうとしていることだとは知りませんでした。ははは、自分のカウンターを書かなければならない場合を除き、私の答えを受け入れないでください! そのためのモジュールがすでにあるようです。

于 2013-07-15T00:47:49.520 に答える
-1

私は Python にあまり熱心ではありませんが、最後の print ステートメントで %s を使用する必要はありませんか?

例: print("最も多く表示された単語: %s", word)

于 2013-07-15T00:08:34.803 に答える