我需要使用正則運算式模塊。我撰寫了這個小程式來替換某些正則運算式匹配,例如用#符號中的橙色長度替換橙色,例如,如果橙色在字串中,那么它將被替換為######。
如果字串已更改,它將添加“!!此字串已更改!!” 到字串的末尾。
如果一個字串沒有改變但是有一個#,那么它就不會添加“!!這個字串已經改變了!!”。
我想知道,有沒有更有效的編碼方式?使用正則運算式函式和更好的 python 代碼。
orange = re.compile(r'\borange\b', re.IGNORECASE)
frog = re.compile(r'\bfrog\b', re.IGNORECASE)
cat = re.compile(r'\bcat\b', re.IGNORECASE)
num = 0
if re.search(orange, s):
s = re.sub(orange, "!!!!!!", s)
num =1
if re.search(frog, s):
s = re.sub(frog, "!!!!", s)
num =1
if re.search(cat, s):
s = re.sub(cat, "!!!", s)
num =1
if num > 0:
return s " !! This string has been changed !!"
else:
return s```
uj5u.com熱心網友回復:
假設您的行輸入可以同時包含 'orange' 'frog' 'cat' 一個特定的解決方案是,創建一個可以匹配任何一個解決方案的正則運算式模式,然后為每個匹配創建一個迭代器,將找到的匹配替換為'x' 根據匹配字串的 len 并列印修改的字串(如果是這種情況,則不列印)
代碼是:
import re
string = "orange frog cat test"
#string = "one two tree testing stackoverflow"
regex_pattern = re.compile(r"\b(orange|frog|cat)\b", re.IGNORECASE)
total_matches = regex_pattern.finditer(string)
# We find either of the options? then changes will be made
changes_done = regex_pattern.search(string)
for match in total_matches:
element_find = match.group(0)
string = regex_pattern.sub("x" * len(element_find), string, 1)
if( changes_done ):
print(string " | changes where made")
else:
print(string " | no changes made")
在這個特定的解決方案中真正閃耀的是 sub 的第三個引數,您可以在其中限制完成的匹配數。正如我所說,為您的問題提供了一種特殊的解決方案。
為替換生成的輸出將是xxxxxx xxxx xxx test | changes where made
uj5u.com熱心網友回復:
我猜您是在函式中使用此代碼,因為您要回傳一些值。
無論如何,沒有num計數器:
import re
pattern = r"\b(orange|frog|cat)\b"
s = "an orange eaten by a frog and a cat"
rgx_matches = re.findall(pattern, s, flags=re.IGNORECASE)
for rgx_match in rgx_matches:
print(re.sub(rgx_match, "#"*len(rgx_match), s) \
" !! This string has been changed !!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491489.html
