gpt4 book ai didi

python - 为什么fuzzywuzzy不考虑字符顺序

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:38 25 4
gpt4 key购买 nike

考虑这个例子:

>> from fuzzywuzzy import process
>> choices = ['account', 'update', 'query']
>> process.extract('u', choices)
[('account', 90), ('update', 90), ('query', 90)]

在上述情况下,对于给定的字符串,account 的排名高于 update 这让我的最终用户感到困惑。在这种情况下,account 恰好由于列表顺序而任意放在前面,因为所有匹配项都共享相同的分数。但是,我原以为 update 会获得更高的分数,仅仅是因为字符 u 在字符串中出现得较早。

这是概念错误还是我没有使用正确的记分器?

最佳答案

首先,您使用的是“糟糕”的得分手。根据您的分数,您可能正在使用 difflib。您应该切换到基于 python-Levenshtein 的实现。这可以通过 scorer 参数来完成。

from fuzzywuzzy import process
from fuzzywuzzy import fuzz

def MyScorer(s1, s2):
fratio = fuzz.ratio(s1, s2)
fratio -= (s2.find(s1)*5)
return fratio

choices = ['account', 'update', 'query']
dex = process.extract('u', choices, scorer=fuzz.token_sort_ratio)
mex = process.extract('u', choices, scorer=MyScorer)
print("Default Scorer:", dex)
print("MyScorer:", mex)

现在输出是

[('query', 33), ('update', 29), ('account', 25)]

哪个更好,但是 Levenshtein 并不真正关心这个位置,

Levenshtein distance (LD) is a measure of the similarity between two strings, which we will refer to as the source string (s) and the target string (t). The distance is the number of deletions, insertions, or substitutions required to transform s into t.

这就是为什么我添加了 MyScorer() 的定义,您可以在其中实现您自己的算法,该算法将位置考虑在内。我还添加了一个考虑位置的实现示例(但我在设计此类算法方面并没有真正的经验,所以不要指望这个算法是完美的甚至可用的)。不管怎样,MyScorer 的输出是:

[('update', 29), ('query', 28), ('account', 5)]

关于python - 为什么fuzzywuzzy不考虑字符顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44299114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com