Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用正则表达式将大写字母转换为title()_Regex_Python 3.x - Fatal编程技术网

Regex 使用正则表达式将大写字母转换为title()

Regex 使用正则表达式将大写字母转换为title(),regex,python-3.x,Regex,Python 3.x,我需要找到文本中所有大写的单词,并将它们命名。我一直在尝试使用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(), t

我需要找到文本中所有大写的单词,并将它们命名。我一直在尝试使用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)
重新导入
text=”“”
这是一些我必须修改的文本
我希望这会很容易
图案=r'(?P[A-Z])(?P[A-Z]+)'
re.sub(pattern,pattern.title(),text)
打印(文本)
我想我需要传递match对象作为第二个参数,但我不知道如何传递。

您可以使用

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)
看到了吗


匹配单词边界内的任何2个或更多大写ASCII字母(作为整个单词)。在lambda表达式中,使用
m.group()
访问匹配值,并在使用
title()
方法修改后返回替换值。

@WiktorStribiżew!为什么不直接使用
+
?@Olivier,因为操作的目的是只处理2个以上字母的单词。当然,只要指出它不会改变任何东西,因为您将匹配已经大写的1个字母的单词
This is Some text that I Have to change
I hope it Would work pretty Easy