- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的数据库中查找相似的食物名称时遇到问题(大约有 10 万个产品名称)。我决定使用 lib fuzzywuzzy
中的 fuzz.token_sort_ratio
来查找类似的产品名称。它是这样工作的:
s1 = 'Pepsi Light'
s2 = 'Light Pepsi'
fuzz.token_sort_ratio(s1, s2)
100
现在我想查找所有具有相似词的产品名称,结果为 fuzz.token_sort_ratio
>= 90这是我的代码:
#Find similar
start=datetime.now()
l = list(v_foods.name[0:20000])
i=0
df = pd.DataFrame(columns=['name1', 'name2', 'probab_same'])
for k in range(len(l)):
for s in range(k+1,len(l)):
probability = fuzz.token_sort_ratio(l[k], l[s])
if probability >= 90:
df.loc[i] = [l[k], l[s], probability]
i +=1
print('Spent time: {}' .format(datetime.now() - start))
df.head(5)
这需要很多时间。我拥有的产品越多,花费的时间就越多
l = list(v_foods.name[0:5000])
花费时间:~3 分钟l = list(v_foods.name[0:10000])
花费时间:~13 分钟l = list(v_foods.name[0:20000])
花费时间:~53 分钟正如我上面所说,我的基地有 10 万个名字,它的工作速度很慢。有什么方法可以优化我的算法吗?
最佳答案
您的问题是您将每个名称与其他名称进行比较。这是 n^2
比较,所以会变慢。您需要做的只是比较有可能足够相似的名称对。
为了做得更好,我们需要知道图书馆实际上在做什么。感谢 this excellent answer我们可以这么说。它在两个名称上调用 fuzz._process_and_sort(name, True)
,然后查找 Levenshtein 比率。也就是说,它计算从一个字符串到另一个字符串的最佳方式,然后计算 100 *matched_chars/(matched_chars + edits)
。要使这个分数达到 90+,编辑次数最多 len(name)/9
。 (这个条件是必要的,但不是充分的,如果这些编辑在这个字符串中包含替换和删除,这会降低匹配字符的数量并降低比率。)
所以你可以很容易地规范化所有的名字。问题是你能找到一个给定的规范化名称,所有其他规范化名称的最大编辑次数吗?
诀窍是首先将所有标准化名称放入 Trie数据结构。然后我们可以并行遍历 Trie 以探索在一定编辑距离内的所有分支。这允许在不单独检查它们的情况下丢弃超出该距离的大量规范化名称。
这是 Trie 的 Python 实现,可让您找到这些规范化名称对。
import re
# Now we will build a trie. Every node has a list of words, and a dictionary
# from the next letter farther in the trie.
class Trie:
def __init__(self, path=''):
self.strings = []
self.dict = {}
self.count_strings = 0
self.path = path
def add_string (self, string):
trie = self
for letter in string:
trie.count_strings += 1
if letter not in trie.dict:
trie.dict[letter] = Trie(trie.path + letter)
trie = trie.dict[letter]
trie.count_strings += 1
trie.strings.append(string)
def __hash__ (self):
return id(self)
def __repr__ (self):
answer = self.path + ":\n count_strings:" + str(self.count_strings) + "\n strings: " + str(self.strings) + "\n dict:"
def indent (string):
p = re.compile("^(?!:$)", re.M)
return p.sub(" ", string)
for letter in sorted(self.dict.keys()):
subtrie = self.dict[letter]
answer = answer + indent("\n" + subtrie.__repr__())
return answer
def within_edits(self, string, max_edits):
# This will be all trie/string pos pairs that we have seen
found = set()
# This will be all trie/string pos pairs that we start the next edit with
start_at_edit = set()
# At distance 0 we start with the base of the trie can match the start of the string.
start_at_edit.add((self, 0))
answers = []
for edits in range(max_edits + 1): # 0..max_edits inclusive
start_at_next_edit = set()
todo = list(start_at_edit)
for trie, pos in todo:
if (trie, pos) not in found: # Have we processed this?
found.add((trie, pos))
if pos == len(string):
answers.extend(trie.strings) # ANSWERS FOUND HERE!!!
# We have to delete from the other string
for next_trie in trie.dict.values():
start_at_next_edit.add((next_trie, pos))
else:
# This string could have an insertion
start_at_next_edit.add((trie, pos+1))
for letter, next_trie in trie.dict.items():
# We could have had a a deletion in this string
start_at_next_edit.add((next_trie, pos))
if letter == string[pos]:
todo.append((next_trie, pos+1)) # we matched farther
else:
# Could have been a substitution
start_at_next_edit.add((next_trie, pos+1))
start_at_edit = start_at_next_edit
return answers
# Sample useage
trie = Trie()
trie.add_string('foo')
trie.add_string('bar')
trie.add_string('baz')
print(trie.within_edits('ba', 1))
关于python - 如何优化算法以更快地找到具有fuzzywuzzy的相似字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64711569/
如何使用 SPListCollection.Add(String, String, String, String, Int32, String, SPListTemplate.QuickLaunchO
我刚刚开始使用 C++ 并且对 C# 有一些经验,所以我有一些一般的编程经验。然而,似乎我马上就被击落了。我试过在谷歌上寻找,以免浪费任何人的时间,但没有结果。 int main(int argc,
这个问题已经有答案了: In Java 8 how do I transform a Map to another Map using a lambda? (8 个回答) Convert a Map>
我正在使用 node + typescript 和集成的 swagger 进行 API 调用。我 Swagger 提出以下要求 http://localhost:3033/employees/sear
我是 C++ 容器模板的新手。我收集了一些记录。每条记录都有一个唯一的名称,以及一个字段/值对列表。将按名称访问记录。字段/值对的顺序很重要。因此我设计如下: typedef string
我需要这两种方法,但j2me没有,我找到了一个replaceall();但这是 replaceall(string,string,string); 第二个方法是SringBuffer但在j2me中它没
If string is an alias of String in the .net framework为什么会发生这种情况,我应该如何解释它: type JustAString = string
我有两个列表(或字符串):一个大,另一个小。 我想检查较大的(A)是否包含小的(B)。 我的期望如下: 案例 1. B 是 A 的子集 A = [1,2,3] B = [1,2] contains(A
我有一个似乎无法解决的小问题。 这里...我有一个像这样创建的输入... var input = $(''); 如果我这样做......一切都很好 $(this).append(input); 如果我
我有以下代码片段 string[] lines = objects.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.No
这可能真的很简单,但我已经坚持了一段时间了。 我正在尝试输出一个字符串,然后输出一个带有两位小数的 double ,后跟另一个字符串,这是我的代码。 System.out.printf("成本:%.2
以下是 Cloud Firestore 列表查询中的示例之一 citiesRef.where("state", ">=", "CA").where("state", "= 字符串,我们在Stack O
我正在尝试检查一个字符串是否包含在另一个字符串中。后面的代码非常简单。我怎样才能在 jquery 中做到这一点? function deleteRow(locName, locID) { if
这个问题在这里已经有了答案: How to implement big int in C++ (14 个答案) 关闭 9 年前。 我有 2 个字符串,都只包含数字。这些数字大于 uint64_t 的
我有一个带有自定义转换器的 Dozer 映射: com.xyz.Customer com.xyz.CustomerDAO customerName
这个问题在这里已经有了答案: How do I compare strings in Java? (23 个回答) 关闭 6 年前。 我想了解字符串池的工作原理以及一个字符串等于另一个字符串的规则是
我已阅读 this问题和其他一些问题。但它们与我的问题有些无关 对于 UILabel 如果你不指定 ? 或 ! 你会得到这样的错误: @IBOutlet property has non-option
这两种方法中哪一种在理论上更快,为什么? (指向字符串的指针必须是常量。) destination[count] 和 *destination++ 之间的确切区别是什么? destination[co
This question already has answers here: Closed 11 years ago. Possible Duplicates: Is String.Format a
我有一个Stream一个文件的,现在我想将相同的单词组合成 Map这很重要,这个词在 Stream 中出现的频率. 我知道我必须使用 collect(Collectors.groupingBy(..)
我是一名优秀的程序员,十分优秀!