
在处理来自外部API(如政府机构、企业数据库)的数据时,一个常见且棘手的问题是数据输入的不一致性。例如,在查询某个特定候选人的捐款记录时,API返回的数据中,该候选人的姓名可能存在多种拼写形式,如“John Smith”、“Jonathan Smith”、“Jon Smith”甚至“John Smyth”等。这些变体可能由人工输入错误、缩写习惯或不同数据源的差异造成。
传统的API查询方法通常依赖于精确匹配。这意味着,如果API仅支持精确匹配,那么我们每次只能查询“John Smith”,而会遗漏“Jonathan Smith”或“Jon Smith”的记录。虽然正则表达式(Regex)在字符串模式匹配方面表现强大,能够处理诸如J.*n Smith这类模式,但多数REST API的设计并不支持在查询参数中直接嵌入复杂的正则表达式进行服务器端过滤。
许多开发者在遇到上述问题时,可能会尝试将正则表达式直接作为API请求的查询参数传递。例如,使用Python的requests库时,可能会尝试将一个编译好的正则表达式对象赋值给参数字典:
import requests
import re
Candidate = r'J.*n Smith'
pattern = re.compile(Candidate)
Payee_Parameter = {
"contribution_payee": pattern, # 尝试将正则表达式对象作为参数传递
"dt_posted": "ascending",
"key": "YOUR_API_KEY" # 替换为你的API Key
}
ContributionsLink = "https://lda.senate.gov/api/v1/contributions/"
response = requests.get(ContributionsLink, params=Payee_Parameter)
# ... 后续处理然而,这种做法通常是无效的。原因在于:
因此,直接在API请求参数中使用正则表达式来处理拼写变体或错别字是不可行的。我们需要一种在API响应数据到达本地后进行处理的策略。
鉴于API的局限性,最有效的解决方案是在本地对从API获取的数据进行“后处理”。这涉及到以下核心思想:
什么是模糊匹配? 模糊匹配是一种字符串相似度比较技术。它通过算法(如Levenshtein距离、Jaro-Winkler距离等)计算两个字符串之间的“距离”或“相似度得分”,得分越高表示字符串越相似。这种技术非常适合识别包含拼写错误、字符顺序颠倒、增删字符或缩写等变体的字符串。
在Python中,fuzzywuzzy库是实现模糊匹配的流行选择。它基于Levenshtein距离,并提供了一系列方便的函数来计算字符串相似度。
在使用之前,需要通过pip安装fuzzywuzzy库。为了获得更好的性能,建议同时安装其依赖的python-Levenshtein库。
pip install fuzzywuzzy python-Levenshtein
fuzz.ratio()函数计算两个字符串之间的简单相似度得分,范围从0到100。得分越高,表示两个字符串越相似。
from fuzzywuzzy import fuzz
# 示例姓名匹配
target_name = "John Smith"
candidates = ["John Smith", "Jonathan Smith", "Jon Smith", "J. Smith", "Johnny Smith", "John Smyth", "Billy Jean"]
print(f"--- 针对 '{target_name}' 的相似度分析 ---")
for candidate in candidates:
score = fuzz.ratio(target_name.lower(), candidate.lower()) # 建议转换为小写进行比较
print(f"'{target_name}' vs '{candidate}': {score}")
# 进一步演示不同相似度
print(f"\nfuzz.ratio('John Doe', 'Joe Dow'): {fuzz.ratio('John Doe', 'Joe Dow')}")
print(f"fuzz.ratio('John Doe', 'John M. Doe'): {fuzz.ratio('John Doe', 'John M. Doe')}")
print(f"fuzz.ratio('John Doe', 'Billy Jean'): {fuzz.ratio('John Doe', 'Billy Jean')}")输出示例:
--- 针对 'John Smith' 的相似度分析 ---
'John Smith' vs 'John Smith': 100
'John Smith' vs 'Jonathan Smith': 87
'John Smith' vs 'Jon Smith': 80
'John Smith' vs 'J. Smith': 67
'John Smith' vs 'Johnny Smith': 87
'John Smith' vs 'John Smyth': 93
'John Smith' vs 'Billy Jean': 22
fuzz.ratio('John Doe', 'Joe Dow'): 67
fuzz.ratio('John Doe', 'John M. Doe'): 84
fuzz.ratio('John Doe', 'Billy Jean'): 22从输出可以看出,John Smith与Jonathan Smith、Jon Smith等变体获得了较高的相似度得分,而与完全不相关的Billy Jean得分很低。
当我们需要在一个字符串列表中查找与给定字符串最相似的一个或多个匹配项时,fuzzywuzzy.process模块提供了便利的函数。
from fuzzywuzzy import process
choices = ["John Smith", "Jonathan Smith", "Jon Smith", "J. Smith", "Johnny Smith", "John Smyth", "Billy Jean"]
query = "John Smith"
# 查找前3个最佳匹配
best_matches = process.extract(query, choices, limit=3)
print(f"\n针对 '{query}' 的前3个最佳匹配:")
for match, score in best_matches:
print(f" - '{match}' (得分: {score})")
# 查找单个最佳匹配
single_best = process.extractOne("Jon Smite", choices) # 故意引入一个拼写错误
print(f"\n针对 'Jon Smite' 的最佳匹配: '{single_best[0]}' (得分: {single_best[1]})")输出示例:
针对 'John Smith' 的前3个最佳匹配: - 'John Smith' (得分: 100) - 'Jonathan Smith' (得分: 87) - 'Johnny Smith' (得分: 87) 针对 'Jon Smite' 的最佳匹配: 'Jon Smith' (得分: 92)
将模糊匹配集成到API数据处理流程的关键在于,理解它是一个本地后处理步骤。
集成步骤概述:
Python代码示例(概念性集成):
import requests
import json
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
# 假设的目标候选人姓名
TARGET_CANDIDATE_NAME = "John Smith"
SIMILARITY_THRESHOLD = 80 # 设置相似度阈值,可根据实际情况调整
# 模拟API响应数据
# 真实场景中,这会是 response.json() 的结果,可能包含多个页面或批次
mock_api_data = [
{"id": 1, "contribution_payee": "John Smith", "amount": 1000, "date": "2023-01-15"},
{"id": 2, "contribution_payee": "Jonathan Smith", "amount": 500, "date": "2023-01-20"},
{"id": 3, "contribution_payee": "Jon Smith", "amount": 200, "date": "2023-01-22"},
{"id": 4, "contribution_payee": "John Smyth", "amount": 750, "date": "2023-02-01"},
{"id": 5, "contribution_payee": "Johnny Smith", "amount": 300, "date": "2023-02-05"},
{"id": 6, "contribution_payee": "J. Smith", "amount": 150, "date": "2023-02-10"},
{"id": 7, "contribution_payee": "Robert Johnson", "amount": 1200, "date": "2023-02-12"},
{"id": 8, "contribution_payee": "Jonathon Smith", "amount":以上就是使用模糊匹配处理API数据中的姓名拼写变体与错别字的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号