一、模糊匹配概述
字元串模糊匹配是指在一個文本中查找與另一個字元串相似的子串。相似程度可以基於多種演算法進行評估,如編輯距離、n-gram、Jaro-Winkler等。
字元串模糊匹配具有很廣的應用場景,如搜索引擎、數據清洗、自然語言處理等。在Python中,字元串模糊匹配也是一項基本功能,可以通過內置函數和第三方包實現。
二、基本函數
Python中的字元串有很多基本函數可以用於模糊匹配,如:
str.count(sub[, start[, end]])
str.find(sub[, start[, end]])
str.startswith(prefix[, start[, end]])
str.endswith(suffix[, start[, end]])
str.count(sub[, start[, end]]) 返回子串sub在str中出現的次數。
s = 'hello world'
count = s.count('l')
print(count) # 3
count = s.count('l', 0, 3)
print(count) # 1
str.find(sub[, start[, end]]) 返回子串sub在str中第一次出現的位置,如果沒有找到則返回-1。
s = 'hello world'
index = s.find('world')
print(index) # 6
index = s.find('python')
print(index) # -1
str.startswith(prefix[, start[, end]]) 和 str.endswith(suffix[, start[, end]]) 分別用於判斷字元串是否以指定前綴或後綴開頭或結尾。
s = 'hello world'
flag = s.startswith('hello')
print(flag) # True
flag = s.endswith('python')
print(flag) # False
三、第三方包
除了上述Python內置函數外,還有許多第三方包可以用於字元串模糊匹配,如re、fuzzywuzzy等。
1. re包
re包是Python中正則表達式的標準庫,可以用於強大的模式匹配。其中,re.search(pattern, string)函數可以用於搜索字元串中是否有與模式匹配的子串。
import re
s = 'hello world'
pattern = 'world'
match_obj = re.search(pattern, s)
if match_obj:
print(match_obj.start(), match_obj.end()) # 6 11
else:
print('not found')
2. fuzzywuzzy包
fuzzywuzzy包是一個基於編輯距離演算法的模糊匹配工具,可以計算兩個字元串之間的相似度。
在使用fuzzywuzzy包之前,需要先安裝:pip install fuzzywuzzy
。
fuzzywuzzy包提供的主要函數如下:
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
ratio = fuzz.ratio('hello', 'hell')
print(ratio) # 80
choices = ['hello', 'hey', 'hi']
result = process.extract('hi', choices, limit=2)
print(result) # [('hi', 100), ('hey', 67)]
fuzzywuzzy包中的fuzz.ratio(s1, s2)函數用於計算字元串s1和s2之間的相似度,返回一個0~100之間的整數,表示相似程度。
fuzzywuzzy包中的process.extract(query, choices, limit=5, scorer=fuzz.WRatio)函數可以用於在一組字元串中查找與指定字元串最相似的幾個字元串。參數中,query為指定字元串,choices為一組字元串,limit為最多返回幾個結果,scorer為自定義的相似度計算函數,默認為編輯距離演算法。
四、結語
Python中的字元串模糊匹配功能是非常強大的,可以通過內置函數和第三方包實現不同的演算法和需求。在實際應用中,應根據具體場景選擇最適合的字元串模糊匹配方法,才能達到最好的效果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/305075.html