我有以下输入:
input = "I love programming with Python-3.3! Do you? It's great... I give it a 10/10. It's free-to-use, no $$$ involved!"
首先,每个句子都应该换行。然后,除了“/”、“'”、“-”、“+”和“$”之外,所有标点符号都应与单词分开。
所以输出应该是:
"I love programming with Python-3 . 3 !
Do you ?
It's great . . .
I give it a 10/10 .
It's free-to-use , no $$$ involved !"
我使用了以下代码:
>>> import re
>>> re.sub(r"([\w/'+$\s-]+|[^\w/'+$\s-]+)\s*", r"\1 ", input)
"I love programming with Python-3 . 3 ! Do you ? It's great ... I give it a 10/10 . It's free- to-use , no $$$ involved ! "
但问题是它不会将句子分成新行。在标点符号和字符之间创建空格之前,如何使用正则表达式来执行此操作?
最佳答案
([!?.])(?=\s*[A-Z])\s*
您可以使用此正则表达式在正则表达式之前创建句子。请参阅演示。替换为 \1\n
。
https://regex101.com/r/sH8aR8/5
x="I love programming with Python-3.3! Do you? It's great... I give it a 10/10. It's free-to-use, no $$$ involved!"
print re.sub(r"([!?.])(?=\s*[A-Z])",r"\1\n",x)
编辑:
(?<![A-Z][a-z])([!?.])(?=\s*[A-Z])\s*
试试这个。查看演示以了解不同的数据集。
关于Python:如何使用正则表达式将句子拆分为新行,然后使用空格将标点符号与单词分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27813744/