首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python ngram计算

Python ngram计算
EN

Stack Overflow用户
提问于 2012-12-28 02:31:06
回答 2查看 298关注 0票数 2

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

代码语言:javascript
运行
复制
from ngram import NGram
print(NGram.compare("coat","hat",N=1))

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

代码语言:javascript
运行
复制
(a-b)/a

其中:

代码语言:javascript
运行
复制
a = total number of distinct ngrams across the two strings
b = number of ngrams NOT shared by the two strings

在我的代码中插入这些值,等于:

代码语言:javascript
运行
复制
(5-3)/5 = 2/5 = 0.4

如果我把代码改成这样:

代码语言:javascript
运行
复制
from ngram import NGram
print(NGram.compare("coata","hata",N=1))

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

代码语言:javascript
运行
复制
(6-3)/6 

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

有谁能解释一下这件事吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-28 08:52:21

在"hata","coat“示例中,gram看起来像这样:

代码语言:javascript
运行
复制
{'a': {'hata': 2, 'coata': 2}, 
'h': {'hata': 1}, 
'c': {'coata': 1}, 
't': {'hata': 1, 'coata': 1}, 
'o': {'coata': 1}}

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

因此,6个中的3个。

票数 1
EN

Stack Overflow用户

发布于 2012-12-28 20:42:13

一个更复杂、更真实的例子--

代码语言:javascript
运行
复制
from ngram import NGram

S1 = "bronchopneumonia"
S2 = "pneumonia"
N = 1

print(NGram.compare(S1,S2,N))

结果是0.5625

公式:

代码语言:javascript
运行
复制
(x-y)/x

其中:

代码语言:javascript
运行
复制
x = total number of distinct ngrams across the two strings
y = number of ngrams NOT shared by the two strings

计算,显示x和y的运行总数:

代码语言:javascript
运行
复制
 'b': {'bronchopneumonia': 1} x=1, y=1
 'r': {'bronchopneumonia': 1} x=2, y=2
 'o': {'bronchopneumonia': 3, 'pneumonia':1} x=5, y=4 
 'n': {'bronchopneumonia': 3, 'pneumonia':2} x=8, y=5 
 'c': {'bronchopneumonia': 1} x=9, y=6
 'h': {'bronchopneumonia': 1} x=10, y=7
 'p': {'bronchopneumonia': 1, 'pneumonia':1} x=11, y=7
 'e': {'bronchopneumonia': 1, 'pneumonia':1} x=12, y=7
 'u': {'bronchopneumonia': 1, 'pneumonia':1} x=13, y=7
 'm': {'bronchopneumonia': 1, 'pneumonia':1} x=14, y=7
 'i': {'bronchopneumonia': 1, 'pneumonia':1} x=15, y=7
 'a': {'bronchopneumonia': 1, 'pneumonia':1} x=16, y=7

这就给我们提供了:

代码语言:javascript
运行
复制
(16-7)/16 = 9/16 = 0.5625

当你在两个字符串中多次出现ngram时,复杂性就会增加。在这个例子中,'o‘和'n’都出现了多次。

代码语言:javascript
运行
复制
'o' appears **3 times** in 'bronchopneumonia' and **1 time** in 'pneumonia'
x now moves to 5 (from 2) and y moves to 4 (from 2).
I think, x is incremented by 3 because it is the higher number???
And I think, y is incremented by 2 because 3-1=2???

‘n’也是如此:

代码语言:javascript
运行
复制
'n' appears **3 times** in 'bronchopneumonia' and **2 times** in 'pneumonia'
x now moves to 8 (from 5) and y moves to 5 (from 4).
I think, x is incremented by 3 because it is the higher number???
And I think, y is incremented by 1 because 3-2=1???

这是我对它工作原理的理解,我不是Python专家,所以我可能误解了源代码中的某些内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14059444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档