Python NLTK:Bigrams卦gramgrams
我有这个例子,我想知道如何得到这个结果。我有文本,我将其标记化,然后收集像这样的二元组,三元组和四元组
import nltk
from nltk import word_tokenize
from nltk.util import ngrams
text = "Hi How are you? i am fine and you"
token=nltk.word_tokenize(text)
bigrams=ngrams(token,2)
二元组: [('Hi', 'How'), ('How', 'are'), ('are', 'you'), ('you', '?'), ('?',
'i'), ('i', 'am'), ('am', 'fine'), ('fine', 'and'), ('and', 'you')]
trigrams=ngrams(token,3)
三联词: [('Hi', 'How', 'are'), ('How', 'are', 'you'), ('are', 'you', '?'),
('you', '?', 'i'), ('?', 'i', 'am'), ('i', 'am', 'fine'), ('am', 'fine',
'and'), ('fine', 'and', 'you')]
bigram [(a,b) (b,c) (c,d)]
trigram [(a,b,c) (b,c,d) (c,d,f)]
i want the new trigram should be [(c,d,f)]
which mean
newtrigram = [('are', 'you', '?'),('?', 'i','am'),...etc
任何想法都会有所帮助
-
如果您应用某种集合论(如果我正确地解释了您的问题),您会发现想要的三元组只是元素的[2:5],[4:7],[6:8]等元素该
token
列表。您可以这样生成它们:
>>> new_trigrams = [] >>> c = 2 >>> while c < len(token) - 2: ... new_trigrams.append((token[c], token[c+1], token[c+2])) ... c += 2 >>> print new_trigrams [('are', 'you', '?'), ('?', 'i', 'am'), ('am', 'fine', 'and')]