我正在嘗試使用正則運算式替換多個專案,但沒有得到預期的輸出。在下面的代碼中,我需要用“X”替換電話號碼和“hi”這個詞
txt = "Hi, my phone number is 089992654231. I am 24 years old."
def processString3(txt):
txt = re.sub('[0-9],Hi]', 'X', txt)
print(txt)
processString3(txt)
預期輸出 - XX, my phone number is XXXXXXXXXX. I am 24 years old.
uj5u.com熱心網友回復:
您可能會發現以下可接受:
txt = "Hi, my phone number is 089992654231. I am 24 years old."
def processString3(txt):
txt = re.sub('[0-9]{5,}|Hi', lambda m: re.sub(r'.', 'X', m.group()), txt)
print(txt)
processString3(txt)
# XX, my phone number is XXXXXXXXXXXX. I am 24 years old.
上述邏輯將目標電話號碼定義為連續的任意 5 位或更多位數字。這將排除年齡,年齡不應超過 3 位數。
uj5u.com熱心網友回復:
您的正則運算式格式錯誤,請嘗試:
import re
def processString3(txt):
phone_number = re.search(r'(\d{5,})', txt)
greetings = re.search(r'(Hi)', txt)
if phone_number:
number_str = phone_number.group(1)
txt = txt.replace(number_str, 'X' * len(number_str))
if greetings:
greeting_str = greetings.group(1)
txt = txt.replace(greeting_str, 'X' * len(greeting_str))
print(txt)
if __name__ == '__main__':
txt = "Hi, my phone number is 089992654231. I am 24 years old."
processString3(txt)
這是一個臨時解決方案,因為您沒有準確指定要隱藏的單詞。如果您提供更多詳細資訊,我可以回傳更有效的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371592.html
上一篇:提取不允許的字符
