我需要从文本中获取最流行的ngram。Ngrams长度必须为1到5个单词。
我知道如何得到大图和三联图。例如:
bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = nltk.collocations.BigramCollocationFinder.from_words(words)
finder.apply_freq_filter(3)
finder.apply_word_filter(filter_stops)
matches1 = finder.nbest(bigram_measures.pmi, 20)
然而,我发现scikit learn可以得到不同长度的ngram。例如,我可以得到长度从1到5的ngram。
v = CountVectorizer(analyzer=WordNGramAnalyzer(min_n=1, max_n=5))
但WordNGramAnalyzer现在已被弃用。我的问题是:如何从我的文本中得到N个最佳词语搭配,搭配长度从1到5。我还需要得到这个搭配的频率表。
我可以用nltk/scikit来做吗?我需要从一个文本中得到不同长度的ngram的组合?
例如,使用NLTK bigrams和trigrams,在许多情况下,我的trigrams包括我的bitgram,或者我的trigrams是更大的4-grams的一部分。例如:
位图:你好,我的 三联图:你好,我的名字
我知道如何从三联图中排除大字,但我需要更好的解决方案。
更新
自scikit学习0.14以来,格式已更改为:
完整示例:
它输出以下内容(注意,单词
I
被删除不是因为它是一个停止字(不是),而是因为它的长度:https://stackoverflow.com/a/20743758/):现在这应该/可能要简单得多,imo.你可以尝试^{} ,但有时这会带来一些复杂的问题,比如初始化一个Doc,它目前在v.0.6.2as shown on their docs中不起作用。If doc initialization worked as promised,理论上,以下方法是可行的(但实际上不行):
旧答案
WordNGramAnalyzer
确实被弃用,因为scikit学习0.11。创建n-grams和获取术语频率现在组合在sklearn.feature_extraction.text.CountVectorizer中。您可以创建从1到5的所有n-grams,如下所示:更多的例子和信息可以在scikit learn关于text feature extraction的文档中找到。
看一下http://nltk.org/_modules/nltk/util.html我认为在幕后nltk.util.bigrams()和nltk.util.trigrams()是使用nltk.util.ngrams()实现的
如果你想生成原始的ngram(或者你自己计算一下),还有
nltk.util.ngrams(sequence, n)
。它将为任何值n生成一个ngram序列。它有填充选项,请参阅文档。如果你想生成原始的ngram(也许你自己计算一下),还有
nltk.util.ngrams(sequence, n)
。它将为任何值n生成一个ngram序列。它有填充选项,请参阅文档。相关问题 更多 >
编程相关推荐