如果您可以返回元组列表,则可以使用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