Python NLTK:Bigrams trigrams fourgrams

时间:2014-06-22 00:16:28

标签: python nltk n-gram

我有这个例子,我想知道如何得到这个结果。我有文字,我对它进行了标记,然后我收集了二元组和三元组以及四元组

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)

bigrams:[('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

任何想法都会有所帮助

4 个答案:

答案 0 :(得分:8)

如果你运用一些集理论(如果我正确地解释你的问题),你会发现你想要的三元组只是元素[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')]

答案 1 :(得分:3)

我这样做:

def words_to_ngrams(words, n, sep=" "):
    return [sep.join(words[i:i+n]) for i in range(len(words)-n+1)]

这会将列表的单词作为输入,并返回ngrams列表(对于给定的n),由sep分隔(在本例中为空格)。

答案 2 :(得分:1)

尝试everygrams

from nltk import everygrams
list(everygrams('hello', 1, 5))

[输出]:

[('h',),
 ('e',),
 ('l',),
 ('l',),
 ('o',),
 ('h', 'e'),
 ('e', 'l'),
 ('l', 'l'),
 ('l', 'o'),
 ('h', 'e', 'l'),
 ('e', 'l', 'l'),
 ('l', 'l', 'o'),
 ('h', 'e', 'l', 'l'),
 ('e', 'l', 'l', 'o'),
 ('h', 'e', 'l', 'l', 'o')]

单词令牌:

from nltk import everygrams

list(everygrams('hello word is a fun program'.split(), 1, 5))

[输出]:

[('hello',),
 ('word',),
 ('is',),
 ('a',),
 ('fun',),
 ('program',),
 ('hello', 'word'),
 ('word', 'is'),
 ('is', 'a'),
 ('a', 'fun'),
 ('fun', 'program'),
 ('hello', 'word', 'is'),
 ('word', 'is', 'a'),
 ('is', 'a', 'fun'),
 ('a', 'fun', 'program'),
 ('hello', 'word', 'is', 'a'),
 ('word', 'is', 'a', 'fun'),
 ('is', 'a', 'fun', 'program'),
 ('hello', 'word', 'is', 'a', 'fun'),
 ('word', 'is', 'a', 'fun', 'program')]

答案 3 :(得分:0)

from nltk.util import ngrams

text = "Hi How are you? i am fine and you"

n = int(input("ngram value = "))

n_grams = ngrams(text.split(), n)

for grams in n_grams :

   print(grams)