M.A*_*san 17 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)
Run Code Online (Sandbox Code Playgroud)
二元语法: [('Hi', 'How'), ('How', 'are'), ('are', 'you'), ('you', '?'), ('?', 'i'), ('i', 'am'), ('am', 'fine'), ('fine', 'and'), ('and', 'you')]
trigrams=ngrams(token,3)
Run Code Online (Sandbox Code Playgroud)
八卦: [('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
Run Code Online (Sandbox Code Playgroud)
任何想法都会有所帮助
如果你应用一些集理论(如果我正确地解释你的问题),你会发现你想要的三元组只是元素[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')]
Run Code Online (Sandbox Code Playgroud)
尝试everygrams:
from nltk import everygrams
list(everygrams('hello', 1, 5))
Run Code Online (Sandbox Code Playgroud)
[出去]:
[('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')]
Run Code Online (Sandbox Code Playgroud)
单词标记:
from nltk import everygrams
list(everygrams('hello word is a fun program'.split(), 1, 5))
Run Code Online (Sandbox Code Playgroud)
[出去]:
[('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')]
Run Code Online (Sandbox Code Playgroud)