对列表中的单词进行计数,并将它们以及出现的次数与Python一起添加到字典中

问题描述 投票:0回答:2

为了清楚起见,我在下面输入我的代码要回答的问题,但是我遇到了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
python list dictionary counting
2个回答
0
投票

尝试一下

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

0
投票

如果我理解的正确,您可以删除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

希望我能为您提供帮助

© www.soinside.com 2019 - 2024. All rights reserved.