我怎样才能使用 nltk 来获得下一个词成为某物的机会?

How can I use nltk to get the chance of the next word being something?

问题

我有一个问题,我有一个词,而对第二个词可能有某些限制(例如 "I _o__")。我想要的是 "rode"、"love" 和 "most" 之类的单词列表,并告诉我每个单词跟随 "I".

的频率有多高

我希望能够得到一个二元组列表 (nextword, probability),其中 nextword 是一个满足正则表达式的词,probability 是 nextword 跟在第一个词之后的概率,由 (number of在文本语料库中的第一个单词之后出现的次数)/(第一个单词出现的次数)。

像这样:

[(nextword, follow_probability("I", nextword) for nextword in findwords('.o..')]

我的方法是首先生成满足正则表达式的可能单词列表,然后查找每个单词的概率。第一部分很容易,但我不知道第二部分怎么做。理想情况下,我可以让一个函数为每个单词接受一个参数,并返回第二个出现在第一个之后的概率。

我试过的

尝试这样的事情:

from collections import Counter, deque
from nltk.tokenize import regexp_tokenize
import pandas as pd

def grouper(iterable, length=2):
    i = iter(iterable)
    q = deque(map(next, [i] * length))
    while True:
        yield tuple(q)
        try:
            q.append(next(i))
            q.popleft()
        except StopIteration:
            break

def tokenize(text):
    return [word.lower() for word in regexp_tokenize(text, r'\w+')]

def follow_probability(word1, word2, vec):
    subvec = vec.loc[word1]
    try:
        ct = subvec.loc[word2]
    except:
        ct = 0
    return float(ct) / (subvec.sum() or 1)

text = 'This is some training text this this'
tokens = tokenize(text)
markov = list(grouper(tokens))
vec = pd.Series(Counter(markov))

follow_probability('this', 'is', vec)

输出:

0.5