-1
# 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
我该如何解决这个问题?我将不胜感激。

4

1 回答 1

0

如果我们调试:

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

如您所见words,for 循环的迭代为我们提供了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) 
于 2019-11-16T11:20:25.687 回答