【发布时间】:2019-11-16 11:12:57
【问题描述】:
# I'm trying to make a Zipf's Law observation using a dictionary that stores every word, and a counter for it. I will later sort this from ascending to descending to prove Zipf's Law in a particular text. I'm taking most of this code from Automate the Boring Stuff with Python, where the same action is performed, but using letters instead.
message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
wordsRanking.setdefault(words[i], 0)
wordsRanking[i] += 1
print(wordsRanking)
这段代码给了我以下错误:
TypeError: list indices must be integers or slices, not str
我该如何解决这个问题?我将不胜感激。
【问题讨论】:
-
因为 i 是一个词,而不是一个索引; Python for 循环遍历元素。
-
许多已经回答的问题可以帮助你。只需在搜索栏中输入您的错误消息
标签: python python-3.x dictionary zipf