换行:
print(kneser_ney.prob('you go to'))
和:
print(kneser_ney.prob('you go to'.split()))
然后它工作正常。当使用从古腾堡项目下载的小说“白鲸记”中的文本作为训练文件时,我得到的值为 0.05217391304347826
通过此修改,您的代码将类似于以下内容:
with open('./txts/mobyDick.txt') as ff:
text = ff.read()
from nltk import word_tokenize,trigrams
from nltk import FreqDist, KneserNeyProbDist
word_tok = word_tokenize(text)
ngrams = trigrams(word_tok)
freq_dist = FreqDist(ngrams)
kneser_ney = KneserNeyProbDist(freq_dist)
print(kneser_ney.prob('you go to'.split()))
此外,这里的所有内容都是在单词级别完成的,而不是在字符级别:
ngrams = trigrams(word_tok)
for _ in range(0,10):
print(next(ngrams))
#('\ufeff', 'The', 'Project')
#('The', 'Project', 'Gutenberg')
#('Project', 'Gutenberg', 'EBook')
#('Gutenberg', 'EBook', 'of')
#('EBook', 'of', 'Moby')
#('of', 'Moby', 'Dick')
#('Moby', 'Dick', ';')
#('Dick', ';', 'or')
#(';', 'or', 'The')
#('or', 'The', 'Whale')
频率分布也在单词级别:
freq_dist.freq(tuple('on the ocean'.split()))
#7.710783916846906e-06
freq_dist.freq(tuple('new Intel CPU'.split()))
#0.0