python 实现模糊匹配
时间: 2023-06-29 15:17:09 浏览: 72
实现模糊匹配的方法有很多,以下是其中一种实现方法:
可以使用 Python 中的 difflib 库,它提供了一些函数用于比较两个字符串的相似度,如 SequenceMatcher、Differ、get_close_matches 等等。
其中,get_close_matches 函数可以用于从一个列表中找到与目标字符串最相似的几个字符串。该函数需要传入三个参数:目标字符串、候选字符串列表、匹配度阈值。匹配度阈值越高,返回的结果越严格。
下面是一个示例代码:
```python
import difflib
def fuzzy_match(target_str, candidate_list, threshold=0.6):
"""
模糊匹配函数
:param target_str: 目标字符串
:param candidate_list: 候选字符串列表
:param threshold: 匹配度阈值,默认为 0.6
:return: 匹配结果列表
"""
result = difflib.get_close_matches(target_str, candidate_list, n=10, cutoff=threshold)
return result
```
使用示例:
```python
target_str = 'apple'
candidate_list = ['banana', 'orange', 'pineapple', 'grape', 'pear']
result = fuzzy_match(target_str, candidate_list)
print(result) # ['pineapple']
```
在这个示例中,函数会将目标字符串 'apple' 与候选字符串列表 ['banana', 'orange', 'pineapple', 'grape', 'pear'] 进行比较,并返回与目标字符串最相似的字符串 'pineapple'。