Skip to main content
 首页 » 编程设计

Python ngram计算

2025年05月04日8lhb25

使用 Python ngram .我的代码如下所示:

from ngram import NGram 
print(NGram.compare("coat","hat",N=1)) 

结果是0.4,计算如下(我觉得!):

(a-b)/a 

地点:

a = total number of distinct ngrams across the two strings 
b = number of ngrams NOT shared by the two strings 

插入我代码中的值等于:

(5-3)/5 = 2/5 = 0.4 

如果我把代码改成这样:

from ngram import NGram 
print(NGram.compare("coata","hata",N=1)) 

结果是 0.5,我不确定这个答案是如何从我上面写的公式中得出的。

(6-3)/6  

这给出了 0.5,但是两个字符串中真的有 6 个不同的 ngram 吗?

任何人都可以阐明这一点吗?

请您参考如下方法:

在“hata”、“coat”的例子中,克数是这样的:

{'a': {'hata': 2, 'coata': 2},  
'h': {'hata': 1},  
'c': {'coata': 1},  
't': {'hata': 1, 'coata': 1},  
'o': {'coata': 1}} 

因此,它将 'a' 的权重加倍。

因此 6 中的 3。