【发布时间】:2020-10-22 00:34:08
【问题描述】:
我在以下数据集中查找文本匹配时遇到了一些困难(请注意,Sim 是我当前的输出,它是通过运行下面的代码生成的。它显示了错误的匹配)。
ID Text Sim
13 fsad amazing ... fsd
14 fdsdf best sport everand the gane of the year❤️❤️❤️❤️... fdsfdgte3e
18 gsd wonderful fast
21 dfsfs i love this its incredible ... reds
23 gwe wonderful end ever seen you ... add
... ... ... ...
261 add wonderful gwe
261 add wonderful gsd
261 add wonderful fdsdf
267 fdsfdgte3e best match ever its a masterpiece fdsdf
277 hgdfgre terrible destroys everything ... tm28
如上图,Sim 没有给出写匹配文本的ID。
例如,add 应该与 gsd 匹配,反之亦然。但我的输出显示 add 与 gwe 匹配,这不是真的。
我使用的代码如下:
from fuzzywuzzy import fuzz
def sim (nm, df): # this function finds matches between texts based on a threshold, which is 100. The logic is fuzzywuzzy, specifically partial ratio. The output should be IDs whether texts match, based on the threshold.
matches = dataset.apply(lambda row: ((fuzz.partial_ratio(row['Text'], nm)) = 100), axis=1)
return [df.ID[i] for i, x in enumerate(matches) if x]
df['L_Text']=df['Text'].str.lower()
df['Sim']=df.apply(lambda row: sim(row['L_Text'], df), axis=1)
df=df.assign(
Sim = df.apply(lambda x: [s for s in x['Sim'] if s != x['ID']], axis=1)
)
def tr (row): # this function assign a similarity score for each text applying partial_ratio similarity
return (df.loc[:row.name-1, 'L_Text']
.apply(lambda name: fuzz.partial_ratio(name, row['L_Text'])))
t = (df.loc[1:].apply(tr, axis=1)
.reindex(index=df.index,
columns=df.index)
.fillna(0)
.add_prefix('txt')
)
t += t.to_numpy().T + np.diag(np.ones(t.shape[0]))
您能帮我理解代码中的错误吗?可惜我看不到。
我的预期输出如下:
ID Text Sim
13 fsad amazing ...
14 fdsdf best sport everand the gane of the year❤️❤️❤️❤️...
18 gsd wonderful add
21 dfsfs i love this its incredible ...
23 gwe wonderful end ever seen you ...
... ... ... ...
261 add wonderful gsd
261 add wonderful gsd
261 add wonderful gsd
267 fdsfdgte3e best match ever its a masterpiece
277 hgdfgre terrible destroys everything ...
因为它在 sim 函数中设置了完美匹配 (=1)。
【问题讨论】:
-
专业提示:如果人们能够理解您的代码,他们更有可能回答。我知道 python 经常鼓励我们编写紧凑的代码,但是如果扩展它并添加一些 cmets,其他人会更容易理解发生了什么。
-
一般来说,最好尝试压缩琐碎的行为并扩展其他所有内容。
-
我添加了一些 cmets 来解释函数的作用。我希望它可以更清楚一点。如果不是,请告诉我。该代码适用于不同的数据集。但是对于上面的数据集,它不起作用,因此它不会选择匹配的文本,而是随机选择的文本。这很奇怪
标签: python pandas fuzzywuzzy