计算字典中每个单词的数量

时间:2013-05-16 01:27:03

标签: string dictionary python-3.x count

我正在尝试修复此代码:

def word_counter (input_str):
    input_str1 = input_str.lower()
    word = 0
    input_str2 = dict(enumerate(input_str1.split(), start=1))
    if word in input_str2:
        input_str2[word] += 1
    else:
        input_str2[word] = 1
    return (input_str2)
word_count_dict = word_counter("This is a sentence")
print(sorted(word_count_dict.items()))

所以不是输出而是:

[(0, 1), (1, 'this'), (2, 'is'), (3, 'a'), (4, 'sentence')]

它将在input_str中返回多个单词的计数,如下所示:

[('a', 1), ('is', 1), ('sentence', 1), ('this', 1)]

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

您可以使用collections.Counter

>>> from collections import Counter
>>> c = Counter('This is a a a sentence'.split())
>>> c
Counter({'a': 3, 'This': 1, 'is': 1, 'sentence': 1})
>>> c['a']
3
>>> c['This']
1
>>> c.items()
[('This', 1), ('a', 3), ('is', 1), ('sentence', 1)]