Files
Python_CookBook_repo/2.字符串和文本/6.不区分大小写的对文本进行匹配和区分大小写的替换.py
2025-09-10 16:12:45 +08:00

35 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
if __name__ == '__main__':
text = "UPPER PYTHON, lower python, mixed Python"
# 想要找到所有的python可以在函数里面找一下有没有flag关键字并设为re.IGNORECASE
pythons = re.findall('python', text, flags=re.IGNORECASE)
print(pythons)
# 但是这样在替换的时候就有问题发生,不能把替换文本的大小写设置成和原文本一样
python_replace = re.sub('python', 'snake', text, flags=re.IGNORECASE)
print(python_replace)
# 这个时候我们需要一个辅助函数
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
# 这个函数将字符串的首字母大写,其余部分转成小写
return word.capitalize()
else:
return word
return replace
python_replace_with_func = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
print(python_replace_with_func)
# 这个辅助函数结构陌生,这里记个笔记备注一下防止以后再看忘记:
# 1.首先sub函数检测到要调用matchcase函数进入函数体返回replace函数 sub->matchcsae
# 2.此时matchcase函数的输入word仍在堆栈中等待调用 matchcase -replace-> sub
# 3.在替换的时候sub函数将识别到的python替换成replace(被识别到的部分) text -> (a1,a2,a3,...)
# 4.replace函数返回大小写处理结果 replace(a1), replace(a2), ...
# 5.函数返回被替换字符串re.sub函数进行替换 将识别到的关键词替换成处理过的word