Say I have a list of tuples, top_n
, of the top n
most common bigrams found in a corpus of text:
import nltk
from nltk import bigrams
from nltk import FreqDist
bi_grams = bigrams(text) # text is a list of strings (tokens)
fdistBigram = FreqDist(bi_grams)
n = 300
top_n= [list(t) for t in zip(*fdistBigram.most_common(n))][0]; top_n
>>> [('let', 'us'),
('us', 'know'),
('as', 'possible')
....
Now I want to replace instances of sets of words that are bigrams in top_n
with their concatenation in place. For example, say we have a new variable query
which is a list of strings:
query = ['please','let','us','know','as','soon','as','possible']
would become
['please','letus', 'usknow', 'as', 'soon', 'aspossible']
after the desired operation. More explicitly, I want to search every element of query
and check if the ith and (i+1)th element are in top_n
; if they are, then replace query[i]
and query[i+1]
with a single concatenated bigram i.e (query[i], query[i+1]) -> query[i] + query[i+1]
.
Is there some way to do this using NLTK, or what would be the best way to do this if looping over each word in query
is necessary?