【问题标题】:Find all the n-grams that contain a certain word efficiently有效地找到包含某个单词的所有 n-gram
【发布时间】:2017-08-02 08:19:02
【问题描述】:

我想从一个文档中生成包含某个单词的所有 n-gram。

例子:

document: i am 50 years old, my son is 20 years old
word: years
n: 2

输出:

[(50, years), (years, old), (20, years), (years, old)]

我知道我们可以生成所有可能的 n-gram 并过滤掉带有单词的那些,但我想知道是否有更有效的方法来做到这一点。我正计划使用 PySpark 来生成它们。

【问题讨论】:

  • 查看 itertools。
  • 嗨!比什么更有效?你现在在做什么?

标签: python apache-spark nlp pyspark n-gram


【解决方案1】:
from nltk.util import ngrams

DOC = 'i am 50 years old, my son is 20 years old'


def ngram_filter(doc, word, n):
    tokens = doc.split()
    all_ngrams = ngrams(tokens, n)
    filtered_ngrams = [x for x in all_ngrams if word in x]
    return filtered_ngrams


ngram_filter(DOC, 'years', 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2017-07-21
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多