1
wordsFreq = {}
words = []
while True:
    inputWord = raw_input()
    if (inputWord != ""):
        words.append(inputWord)
    else:
        break
for word in words:
    wordsFreq[word] = wordsFreq.get(word, 0) + 1

for word,freq in wordsFreq.items():
    print word + " - " + str(freq)

显然我的 words[] 和 for 循环是多余的,但我没有进一步的解释,谁能向我解释为什么它是多余的?

4

4 回答 4

7

您可以跳过构建单词列表的步骤,而是在用户输入单词时直接创建频率字典。我过去常常defaultdict避免检查是否已经添加了一个单词。

from collections import defaultdict

wordsFreq = defaultdict(int)
while True:
    word = raw_input()
    if not word:
        break
    wordsFreq[word] += 1

如果您不允许使用defaultdict,它可能如下所示:

wordsFreq = {}
while True:
    word = raw_input()
    if not word:
        break
    wordsFreq[word] = wordFreq.get(word, 0) + 1
于 2012-04-23T12:16:19.023 回答
2

You can use collections.Counter to do this easily:

from collections import Counter

words = []
input_word = True
while input_word:
    input_word = raw_input()
    words.append(input_word)

counted = Counter(words)

for word, freq in counted.items():
    print word + " - " + str(freq)

Note that an empty string evaluates to false, so rather than breaking when it equals an empty string, we can just use the string as our loop condition.

Edit: If you don't wish to use Counter as an academic exercise, then the next best option is a collections.defaultdict:

from collections import defaultdict

words = defaultdict(int)
input_word = True
while input_word:
    input_word = raw_input()
    if input_word:
        words[input_word] += 1

for word, freq in words.items():
    print word + " - " + str(freq)

The defaultdict ensures all keys will point to a value of 0 if they havn't been used before. This makes it easy for us to count using one.

If you still want to keep your list of words as well, then you would need to do that in addition. E.g:

words = []
words_count = defaultdict(int)
input_word = True
while input_word:
    input_word = raw_input()
    if input_word:
        words.append(input_word)
        words_count[input_word] += 1
于 2012-04-23T12:14:58.950 回答
2

我想你的老师想说你可以这样写循环

wordsFreq = {}
while True:
    inputWord = raw_input()
    if (inputWord != ""):
        wordsFreq[inputWord] = wordsFreq.get(inputWord, 0) + 1
    else:
        break

for word,freq in wordsFreq.items():
    print word + " - " + str(freq)

无需将单词存储在临时列表中,您可以在阅读时计算它们

于 2012-04-23T13:27:37.070 回答
0

You can do this:

wordsFreq = {}
while True:
    inputWord = raw_input()
    try:
         wordsFreq[inputWord] = wordsFreq[inputWord] + 1
    except KeyError:
         wordsFreq[inputWord] = 1
于 2012-04-23T12:13:57.870 回答