我想找出字串中是否包含子字串并將其從其中洗掉而不觸及字串的其余部分。問題是我必須執行搜索的子字串模式并不完全是字串中包含的內容。特別是問題是由于西班牙口音的人聲,同時還有大寫的子字串,例如:
myString = 'I'm júst a tésting stríng'
substring = 'TESTING'
執行某些操作以獲得:
resultingString = 'I'm júst a stríng'
現在我已經讀過那個difflib庫可以比較兩個字串并以某種方式加權它的相似性,但我不確定如何為我的案例實作這個(沒有提到我沒有安裝這個庫)。
謝謝!
uj5u.com熱心網友回復:
這種normalize()方法可能有點矯枉過正,也許使用https://stackoverflow.com/a/71591988/218663上的 @Harpe 的代碼可以正常作業。
在這里,我要將原始字串分解為“單詞”,然后將所有不匹配的單詞重新組合成一個字串:
import unicodedata
def normalize(text):
return unicodedata.normalize("NFD", text).encode('ascii', 'ignore').decode('utf-8').lower()
myString = "I'm júst a tésting stríng"
substring = "TESTING"
newString = " ".join(word for word in myString.split(" ") if normalize(word) != normalize(substring))
print(newString)
給你:
I'm júst a stríng
如果您的“子字串”可能是多字,我可能會考慮將策略切換為正則運算式:
import re
import unicodedata
def normalize(text):
return unicodedata.normalize("NFD", text).encode('ascii', 'ignore').decode('utf-8').lower()
myString = "I'm júst á tésting stríng"
substring = "A TESTING"
match = re.search(f"\\s{ normalize(substring) }\\s", normalize(myString))
if match:
found_at = match.span()
first_part = myString[:found_at[0]]
second_part = myString[found_at[1]:]
print(f"{first_part} {second_part}".strip())
我認為這會給你:
I'm júst stríng
uj5u.com熱心網友回復:
您可以使用該包unicodedata將重音字母標準化為 ascii 代碼字母,如下所示:
import unicodedata
output = unicodedata.normalize('NFD', "I'm júst a tésting stríng").encode('ascii', 'ignore')
print(str(output))
這會給
b"I'm just a testing string"
然后,您可以將其與您的輸入進行比較
"TESTING".lower() in str(output).lower()
應該回傳True。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448798.html
