Reputation: 972
I just started working with nltk and python, and I am having a small problem while iterating over the list of bigrams returned by nltk.
Example of what I want:
this is the list of bigrams: [('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]
What I want is to be able to get each bigram : (more,is) and each term of each bigram:more, is etc separately
Here is what I tried so far, based on some answers in stackoverflow:
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
I assume that this bigrams are a list of tuples, so what am I doing wrong?
Can you please point me out to any working code or tutorial. I will also be happy to accept any correct answer.
Thank you in advance
Note: I am working with python 2.7
Upvotes: 0
Views: 1543
Reputation: 107287
for iterating inside a tuple you need just use variables (with the number of bigram
indexes ) not tuple like this:(for (a, b) in bigrams
) , and if you just want each bigram
use ONE variable
in your loop :
for better understanding see the below Demo :
>>> 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')
>>>
Upvotes: 1