对列表中的单词进行计数并将它们添加到字典中,连同出现次数 Python

Count words in a list and add them to a dictionary, along with number of occurrences Python

为清楚起见,我将在下方输入我的代码所回应的问题,但我遇到了 2 个问题。它似乎正确地添加了一个点,并且句子中其他单词的计数结果似乎是准确的,但是兔子突然从 1 跳到 4,我不确定为什么。

我也得到这个:错误:AttributeError:'int' 对象没有属性 'items'

这是我的代码遇到的问题。谢谢!

提供的是字符串保存到变量名的句子。将字符串拆分为单词列表,然后创建一个包含每个单词及其出现次数的字典。将这个字典保存到变量名word_counts.

sentence = "The dog chased the rabbit into the forest but the rabbit was too quick."
sentence_case = sentence.lower()
sentence_list = sentence_case.split()
sentence_dictionary = {}
word_counts = 0

for item in sentence_list:
    if item in sentence_dictionary:
        word_counts += 1
        sentence_dictionary[item] = word_counts

    else:
        sentence_dictionary[item] = 1

试试这个

sentence = "The dog chased the rabbit into the forest but the rabbit was too quick."
sentence_case = sentence.lower()
sentence_list = sentence_case.split()
sentence_dictionary = {}

for item in sentence_list:
    if item in sentence_dictionary:
        sentence_dictionary[item] += 1

    else:
        sentence_dictionary[item] = 1

如果,我理解你是对的,你可以删除 word_count 变量来计算单词的频率

sentence = "The dog chased the rabbit into the forest but the rabbit was too quick."
sentence_case = sentence.lower()
sentence_list = sentence_case.split()
sentence_dictionary = {}

for item in sentence_list:
    if item in sentence_dictionary:
        sentence_dictionary[item] += 1

    else:
        sentence_dictionary[item] = 1

print(sentence_dictionary)

如果你想在 word_counts 中保存它,你可以这样做:

word_counts = sentence_dictionary

希望能帮到你

变量word_counts背后的目的是什么?此变量的当前用法混淆了不同单词的计数。您的问题现在减少为每个单词都有不同的计数器。幸运的是,你不需要明确地这样做,因为 sentence_dictionary 是一组独立的计数器:)只需在你的 if 下增加 sentence_dictionary[item]阻止并删除 word_counts.

作为旁注,这是一个利用 Python 提供的 defaultdict class 的好例子。 defaultdict 与 default_factory 作为参数一起初始化。这允许您初始化计数、列表、集合等的字典,而无需显式处理边缘情况。

考虑下面的代码示例:

dic = defaultdict(int)
dic[0] += 1
dic[0] # prints 1

如果你注意到了,我不必明确检查字典中是否存在键,因为 defaultdict class 通过自动创建值为 0 的键(值 0 因为default_factory 是 int())。您可以浏览 Python 文档以了解 defaultdict 的工作原理。它会为您节省一些时间和以后的调试!

你可以试试这个,对我有用。

sentence = "The dog chased the rabbit into the forest but the rabbit was too quick."
sentence_list = sentence.split()
sentence_dictionary = {}

for item in sentence_list:
    if item not in sentence_dictionary:
        sentence_dictionary[item] = 0
    sentence_dictionary[item] += 1
word_counts = sentence_dictionary
print(word_counts)