为什么在这个Python程序中会出现TypeError?

为什么在这个Python程序中会出现TypeError?,python,python-3.x,dictionary,zipf,Python,Python 3.x,Dictionary,Zipf,此代码给出了以下错误: 类型错误:列表索引必须是整数或切片,而不是str 我如何解决这个问题?如果我们调试: # 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 particu

此代码给出了以下错误:
类型错误:列表索引必须是整数或切片,而不是str
我如何解决这个问题?如果我们调试:

# 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)    
结果是:

message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    print(i) ### add this
    wordsRanking.setdefault(words[i], 0)
    wordsRanking[i] += 1   
print(wordsRanking)   

因为我是一个词,不是索引;Python for循环在元素上迭代。已经回答的许多问题可以帮助您。只需在搜索栏中键入错误消息
the ## this is what printed. and word[i] is now equal to word["the"]. that raise an error
Traceback (most recent call last):
  File "C:\Users\Dinçel\Desktop\start\try.py", line 6, in <module>
    wordsRanking.setdefault(words[i], 0)
TypeError: list indices must be integers or slices, not str
message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    wordsRanking.setdefault(i, 0)
    wordsRanking[i] += 1   
print(wordsRanking)