python模糊匹配指定字符
时间: 2023-10-23 17:09:44 浏览: 31
可以使用模糊匹配库fuzzywuzzy来实现。安装fuzzywuzzy库:
```
pip install fuzzywuzzy
```
然后可以使用其中的`process`函数来进行模糊匹配。例如,假设你要从一个列表中找到与"apple"最相似的单词,可以这样做:
```python
from fuzzywuzzy import process
words = ["apples", "banana", "orange", "peach"]
search_word = "apple"
best_match, score = process.extractOne(search_word, words)
print("Best match:", best_match)
print("Score:", score)
```
输出:
```
Best match: apples
Score: 90
```
`extractOne`函数会返回找到的最佳匹配结果和匹配得分。匹配得分越高,说明匹配越相似。如果需要返回多个匹配结果,可以使用`extract`函数。例如,假设你要找到与"apple"相似度较高的单词,可以这样做:
```python
from fuzzywuzzy import process
words = ["apples", "banana", "orange", "peach"]
search_word = "apple"
matches = process.extract(search_word, words)
for match in matches:
print("Match:", match[0])
print("Score:", match[1])
```
输出:
```
Match: apples
Score: 90
Match: apple
Score: 86
Match: ape
Score: 67
Match: chapel
Score: 57
```
阅读全文