Подтвердить что ты не робот

Python NLTK: триграммы триграмм Bigrams

У меня есть этот пример, и я хочу знать, как получить этот результат. У меня есть текст, и я его токенизирую, тогда я собираю биграмм и триграмм и четырехграмм, таких как

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

любая идея будет полезна

4b9b3361

Ответ 1

Если вы примените некоторую теорию множеств (если я правильно интерпретирую ваш вопрос), вы увидите, что триграммы, которые вы хотите, - это просто элементы [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')]

Ответ 2

Я делаю это так:

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 (в данном случае пробелом).

Ответ 3

Попробуйте 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')]

Ответ 4

from nltk.util import ngrams

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

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

if n == 3:

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

    for grams in trigrams:

      print(grams)

elif n == 2:

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

    for grams in bigrams:

      print(grams)

else:

    pass

Ответ 5

from nltk.util import ngrams

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

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

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

for grams in trigrams:

   print(grams)