我需要在文本中找到所有大写的单词并将其标题化。我一直试图用re.sub做这个,但我无法弄清楚第二个参数应该是什么。我试过了:
import re
text = """
This is SOME text that I HAVE to change
I hope it WOULD work pretty EASY"""
pattern = r'(?P<b>[A-Z])(?P<a>[A-Z]+)'
re.sub(pattern, pattern.title(), text)
print(text)
我想我需要将匹配对象作为第二个参数传递,但我不知道该怎么做。
答案 0 :(得分:2)
您可以使用
import re
text = """This is SOME text that I HAVE to change
I hope it WOULD work pretty EASY"""
pattern = r'\b[A-Z]{2,}\b'
text = re.sub(pattern, lambda x: x.group().title(), text)
print(text)
请参阅Python demo让步
This is Some text that I Have to change
I hope it Would work pretty Easy
\b[A-Z]{2,}\b
regex匹配单词边界内的任何2个或更多大写ASCII字母(作为整个单词)。在lambda表达式中,使用m.group()
访问匹配值,并在使用title()
方法修改后将其作为替换值返回。