Python正则表达式:替换后跟空格的点和符号

2024-10-01 15:36:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想替换dot/?/ ! 后跟空格(如果有)到特征线字符\n,并消除空白。 所以对于:hello world. It's nice.我希望它是hello world.\nIt'snice.\n
这就是我所想的(但它行不通,否则我就不会写这个问题了哈?)在

re.sub(r'\.!?( *)', r'.\n\1', line)

谢谢!在


Tags: rehelloworldlineit特征字符dot
3条回答

将空格或字符串的结尾与后面的正视图匹配:

re.sub(r'(?<=[.?!])( +|\Z)', r'\n', text)

因为这只匹配前面有标点符号的空格,所以不需要使用反向引用。在

+确保此处只匹配后跟空格的标点符号。正文:

^{pr2}$

否则会收到太多的新行。在

演示:

>>> import re
>>> text = "hello world. It's nice."
>>> re.sub(r'(?<=[.?!])( +|\Z)', r'\n', text)
"hello world.\nIt's nice.\n"
>>> text = "His thoughts trailed away... His heart wasn't in it!"
>>> re.sub(r'(?<=[.?!])( +|$)', r'\n', text)
"His thoughts trailed away...\nHis heart wasn't in it!\n"

无需环顾:

>>> import re
>>> line="hello world! What? It's nice."
>>> re.sub(r'([.?!]+) *', r'\1\n', line)   # Capture punctuations; discard spaces
"hello world!\nWhat?\nIt's nice.\n"

>>> line="hello world! His thoughts trailed away... What?"
>>> re.sub(r'([.?!]+) *', r'\1\n', line)
'hello world!\nHis thoughts trailed away...\nWhat?\n'

你试过replace?在

print text.replace('. ','.\n').replace('? ','?\n').replace('! ','!\n')

相关问题 更多 >

    热门问题