我有這段代碼來查找字串中的匹配項,我在搜索中使用來標記與我的搜索匹配的單詞,我需要它不區分大小寫,這里的問題是它用我們搜索的單詞替換了單詞。
val_to_searchp = "this Text string has alot of teXt"
word = "TEXT"
pal2rep = str(":::") word str(":::")
val_to_search = re.sub(re.escape(word), pal2rep, val_to_searchp, flags=re.IGNORECASE)
這將回傳
"this :::TEXT::: string has alot of :::TEXT:::"
我需要它回傳
"this :::Text::: string has alot of :::teXt:::"
也嘗試過,但效果不佳:(
f = 0
s = 0
val_to_search = val_to_searchp
for m in re.finditer(str(word), str(val_to_searchp)):
inicio = int(m.start() s)
fim = int(m.end() f)
val_to_search = val_to_search[:inicio] \
str(":::") \
val_to_search[inicio:fim] \
str(":::") \
val_to_search[fim:].strip()
f = f 2
s = s 1
這是我的實際代碼
def findtext():
if len(str(findtext_inp.get('1.0', END)))>1:
val_to_searchp = str(respon_txt.get(1.0, END).replace(html.unescape('⛔'), "").strip())
respon_txt.delete(1.0, END)
word = str(findtext_inp.get('1.0', END).strip())
pal2rep = str(str(html.unescape('⛔')) word str(html.unescape('⛔')))
val_to_search = re.sub(re.escape(word), pal2rep, val_to_searchp, flags=re.IGNORECASE)
"""
f = 0
s = 0
for m in re.finditer(str(word), str(val_to_search)):
inicio = int(m.start() s)
fim = int(m.end() f)
val_to_search = val_to_search[:inicio] \
str(html.unescape('⛔')) \
val_to_search[inicio:fim] \
str(html.unescape('⛔')) \
val_to_search[fim:].strip()
f = f 2
s = s 1
"""
respon_txt.insert(1.0, val_to_search)#val_to_search.replace(findtext_inp.get('1.0', END).strip() , str(html.unescape('⛔') findtext_inp.get('1.0', END).strip()) html.unescape('⛔')))
uj5u.com熱心網友回復:
我確信有一種方法可以使用 RE 做到這一點,但如果沒有該模塊的幫助,它真的很簡單。
val_to_searchp = "this Text string has alot of teXt\nThis also has a lot of text"
text = 'TEXT'
def func(s, txt):
txt = txt.lower()
result = []
for line in s.split('\n'):
for i, e in enumerate(t := line.split()):
if e.lower() == txt:
t[i] = f':::{e}:::'
result.append(' '.join(t))
return '\n'.join(result)
print(func(val_to_searchp, text))
輸出:
this :::Text::: string has alot of :::teXt:::
This also has a lot of :::text:::
uj5u.com熱心網友回復:
這是對我原來答案的重寫。在該答案的評論中,您會看到 OP 已經改變了關于如何作業的想法。現在(希望)這符合更改后的規范:
val_to_searchp = '''{\"configurationKey\":[{\"key\":\"GetMaxKeys\",\"readonly\":true,\"value\":\"20\"}'''
text = 'GetMaxKeys'
def func(s, txt):
result = []
sl = s.lower()
txt = txt.lower()
lt = len(txt)
offset = 0
while (i := sl[offset:].find(txt)) >= 0:
result.append(s[offset:i offset])
offset = i
result.append(f':::{s[offset:offset lt]}:::')
offset = lt
result.append(s[offset:])
return ''.join(result)
print(func(val_to_searchp, text))
輸出:
{"configurationKey":[{"key":":::GetMaxKeys:::","readonly":true,"value":"20"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453161.html
標籤:Python python-3.x
上一篇:使用for回圈和字典
