2014-09-30 64 views
0

我刚开始使用nltk和python,并且在遍历由nltk返回的bigrams列表时遇到一个小问题。我想要什么迭代由nltk给出的bigrams(元组):TypeError:'NoneType'对象不可迭代,Python

例子:

这是双字母组名单: [( '更多', '是'),( '是', '说'),( '说',“比“),(”不是”,‘完成’)]

我要的是能够得到每个两字:(更多是),每个二元的每个术语:更多的,是等分别

这是我到目前为止,基于在计算器中的一些答案:

bigrams = nltk.bigrams(doclist) 

#method 1 
for (a, b) in bigrams: #I get this error: TypeError: 'NoneType' object is not iterable 
    print a 
    print b 

#method 2 
#convert to a list first 
bigrams = list(bigrams)# I get the same error 
for (a, b) in bigrams: 
    print a 
    print b 

#method 3 
#convert to a dict first 
dct = dict(tuples)# I get the same error 

我认为这个bigrams是一个元组列表,所以我做错了什么?

你可以请我指出任何工作代码或教程。我也很乐意接受任何正确的答案。

预先感谢您

注:我使用Python 2.7

+0

您的第一次尝试对我有效:'for(a,b)in bigrams:' 如果此时'bigrams'为None,那就可以解释您得到的错误。 – Celeo 2014-09-30 17:30:02

+0

是的,这是多么愚蠢!我忘记了我使用的函数中的return语句,所以bigrams是None。感谢您的观察 – sel 2014-09-30 17:42:08

回答

1

工作你只需要使用变量(与bigram指标数)的元组内不迭代元组这样的:(for (a, b) in bigrams) ,如果你只是希望每个bigram使用ONE variable在循环:

为了更好地理解看到下面的演示:

>>> bigrams=[('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')] 
>>> for a, b in bigrams: 
...  print a 
...  print b 
... 
more 
is 
is 
said 
said 
than 
than 
done 
>>> for a in bigrams: 
... print a 
... 
('more', 'is') 
('is', 'said') 
('said', 'than') 
('than', 'done') 
>>>