2016-12-18 72 views
0

我试图从一个句子中获取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

提示:当你最后一个词时会发生什么? –

+0

'单词!=句子[-1]或句子[-2]':那不是你想要做的。 –

+0

我无法用最后两个单词作为第一个单词构建卦(right,now,???),所以我不会对它们做任何事情。因此,测试当前单词是最后两个单词之一。 – spiderkitty

回答

0

我猜if word != sentence[-1] or sentence[-2]是不是你想要的。你的意思是if word != sentence[-1] and word != sentence[-2],意思word不等于sentence[-1]也不等于sentence[-2]

+0

哦,是的,这实际上是造成这个问题的原因:D非常感谢,现在正在工作! – spiderkitty

0

您可以使用列表作为你的元组的内容都是相同的数据类型(串)

的它可能更容易做:

trigrams = [] 
sentence = ["What", "is", "happening", "right", "now"] 

for i in range(2,len(sentence)): 
    trigrams.append([sentence[i-2],sentence[i-1],sentence[i]]) 
+0

是的,这实际上看起来更容易,但我需要测试,如果他们在字典中是遗传的。但是,我发现我的错误。感谢你们对我的帮助! – spiderkitty

0

给你想保持你的代码结构的元组和最低限度地改变你的代码,你可以做到这一点(不是说这可能是你的问题的好办法,等):

trigrams = {} 
sentence = ["What", "is", "happening", "right", "now"] 

for index, word in enumerate(sentence): 
    print index, word # to understand how the iteration goes on 
    if index < len(sentence)-2: 
     if tuple((word, sentence[index+1], sentence[index+2])) not in trigrams: 
      trigrams.update({tuple((word, sentence[index+1], sentence[index+2])):1}) 

你得到一个索引错误是因为你正在访问一个在tuple()中不存在的元素......因为你检查的方式是否接近列表的末尾(最后两个元素)wasn'没错。

你正在使用的代码:

if word != sentence[-1] or sentence[-2] 

是不对的,你最后,而不是指标比较字符串,这是这里重要的!比较索引,而不是这些位置的值。

+0

是的,它工作,我用“和”替换了“或”。感谢你们对我的帮助! – spiderkitty

相关问题