【问题标题】:How can I find a specific bigram using nltk in python?如何在 python 中使用 nltk 找到特定的二元组?
【发布时间】:2020-11-14 15:13:47
【问题描述】:

我目前正在使用 nltk.book iny Python 并希望找到特定二元组的频率。我知道有 bigram() 函数可以为您提供文本中最常见的二元组,如下代码所示:

    >>> list(bigrams(['more', 'is', 'said', 'than', 'done']))
    [('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]
    >>>

但是,如果我只搜索“wish for”之类的特定内容怎么办?到目前为止,我在 nltk 文档中找不到任何相关内容。

【问题讨论】:

  • 所以你想要“希望”的频率?请添加预期输出
  • @DaniMesejo 是的,输出应该类似于“Wish for: 5”。不过,我的问题现在已经解决了。 :)

标签: python nltk frequency nltk-book


【解决方案1】:

如果可以返回元组列表,可以使用in

>>> bgrms = [('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]
>>> ('more', 'is') in bgrms
True
>>> ('wish', 'for') in bgrms
False

如果您正在寻找特定二元组的频率,构建计数器可能会有所帮助:

from nltk import bigrams
from collections import Counter

bgrms = list(bigrams(['more', 'is', 'said', 'than', 'wish', 'for', 'wish', 'for']))

bgrm_counter = Counter(bgrms)

# Query the Counter collection for a specific frequency:
print(
  bgrm_counter.get(tuple(["wish", "for"]))
)

输出:

2

最后,如果您想根据可能的二元组数来理解这个频率,您可以除以可能的二元组数:

# Divide by the length of `bgrms`

print(
  bgrm_counter.get(tuple(["wish", "for"])) / len(bgrms)
)

输出:

0.2857142857142857

【讨论】:

  • 谢谢你,回答了我的问题!
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多