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

String 计算字典中每个单词的数量,string,dictionary,python-3.x,count,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

我正在尝试修复此代码:

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')]
相反,它将返回输入中每个单词的数量,如下所示:

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

任何帮助都将不胜感激

您可以使用
集合。计数器

>>> 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)]