Python NLTK:Bigrams卦gramgrams

发布于 2021-01-29 15:15:54

我有这个例子,我想知道如何得到这个结果。我有文本,我将其标记化,然后收集像这样的二元组,三元组和四元组

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

任何想法都会有所帮助

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您应用某种集合论(如果我正确地解释了您的问题),您会发现想要的三元组只是元素的[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')]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看