我试图从一个句子中获取trigrams并将它们保存在字典中,并将它们的频率值作为值。 我写这样的:为什么我得到一个IndexError?
trigrams = {}
sentence = ["What", "is", "happening", "right", "now"]
for word in sentence:
if word != sentence[-1] or sentence[-2] and tuple((word, sentence[sentence.index(word) +1], sentence[sentence.index(word) +2])) not in trigrams:
trigrams.update({tuple((word, sentence[sentence.index(word) +1], sentence[sentence.index(word) +2])):1})
应该是这样的: ( “什么”, “是”, “新锐”):1 ( “是”, “新锐”, “右”):1 etc
但现在我不断收到更新行中的IndexError。
提示:当你最后一个词时会发生什么? –
'单词!=句子[-1]或句子[-2]':那不是你想要做的。 –
我无法用最后两个单词作为第一个单词构建卦(right,now,???),所以我不会对它们做任何事情。因此,测试当前单词是最后两个单词之一。 – spiderkitty