You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用fuzzywuzzy从无空格长字符串中提取匹配子串?

问题:thefuzz的process.extract返回单个字符而非预期的部分匹配序列

你使用thefuzz(原fuzzywuzzy)的process.extract方法对无空格长字符串做模糊搜索时,遇到了返回结果为单个字符/数字,而非fuzz.partial_ratio检测到的完整匹配序列的问题。

代码与运行结果

你的测试代码:

from thefuzz import fuzz, process

target = "1234"
source = "012345"
print(fuzz.partial_ratio(target, source))
print(process.extract(target, source, limit=2))

运行后:

  • fuzz.partial_ratio输出100,说明目标字符串是源字符串的子串
  • process.extract却返回:
[('1', 90), ('2', 90)]

而非预期的:

[('1234', 100)]

问题原因

process.extract的第二个参数要求是可迭代的序列(如列表、元组),你传入的是单个字符串"012345",Python会将字符串拆解为单个字符的迭代器,所以process.extract会逐个字符和target做匹配,最终返回单个字符的匹配结果。

解决办法

方法1:将源字符串包装为列表

把source放进列表中,让process.extract把整个字符串作为匹配对象:

from thefuzz import fuzz, process

target = "1234"
source = ["012345"]  # 改为列表形式
print(fuzz.partial_ratio(target, source[0]))
print(process.extract(target, source, limit=2))

运行结果:

100
[('012345', 100)]

方法2:提取源字符串中匹配的子串

如果需要从源字符串中直接提取出和target匹配的子串,可以遍历源字符串的所有等长子串,结合fuzz.partial_ratio筛选:

from thefuzz import fuzz

target = "1234"
source = "012345"
target_length = len(target)
matched_substrings = []

# 遍历所有可能的等长子串
for i in range(len(source) - target_length + 1):
    current_substring = source[i:i+target_length]
    if fuzz.partial_ratio(target, current_substring) == 100:
        matched_substrings.append(current_substring)

print(matched_substrings)  # 输出 ['1234']

内容的提问来源于stack exchange,提问作者Bas Jansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:32:54