Python:如何使用正则表达式将句子拆分为新行,然后使用空格将标点符号与单词分开?

标签 python regex

我有以下输入:

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*

试试这个。查看演示以了解不同的数据集。

https://regex101.com/r/sH8aR8/9

关于Python:如何使用正则表达式将句子拆分为新行,然后使用空格将标点符号与单词分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27813744/

相关文章:

Python - 编写伪代码?

python - 使用networkx的最短路径的边属性

ruby-on-rails - 验证 : Only letters, 数字和 -

javascript - 如何使用正则表达式在字符串中间加1

python - 我如何为这些网址编写正则表达式

Python:如何从列表中删除价低于特定值的值

python - 跨 LiveServerTestCase 测试方法保留数据?

python - 保护多线程程序中的关键部分

regex - 使用shell脚本格式化文本文件内容

javascript - 非数字正则表达式 + 仅允许单个 "."用于输入验证