为什么我会在这个 Python 程序中得到 TypeError?

Why do I get a TypeError in this Python program?

# 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: 列表索引必须是整数或切片,而不是 str
我该如何解决这个问题?我将不胜感激。

如果我们调试:

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)   

输出是:

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

如您所见,通过 for 循环迭代 words 会得到 word 的元素。不是元素的整数或索引。所以你应该使用 wordsRanking.setdefault(i, 0):

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