簡體   English   中英

計算列表中的單詞並將它們添加到字典中,以及出現次數 Python

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

為了清楚起見,我將在下面輸入我的代碼要回答的問題,但我遇到了 2 個問題。 它似乎正確地添加到一個點,並且句子中其他單詞的計數結果似乎是准確的,但是兔子突然從 1 跳到 4,我不知道為什么。

我也得到這個:錯誤:AttributeError:'int' object has no attribute '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

如果,我理解你的權利,你可以刪除 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

我希望我能幫助你

嘗試這個

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_counts背后的目的是什么? 此變量的當前使用將不同單詞的計數混為一談。 您的問題現在減少到為每個單詞設置不同的計數器。 幸運的是,您不需要顯式執行此操作,因為sentence_dictionary本身就是一組計數器:) 只需在 if 塊下增加 sentence_dictionary[item] 並去掉word_counts

作為旁注,這是利用Python提供的默認字典 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM