首页 > 解决方案 > Python中的单引号换行

问题描述

我现在在 Python 中有这个:

"Going to school.
Taking a few courses and playing basketball.
Got a new puppy."
"Going to school.
I bought a new backpack yesterday.
Got a new cat.
I did my homework as well."
"Going to school.
Brought lunch today."

我试图弄清楚我是如何从任何时候开始在这里放置换行符的,"所以我在每行的引号中都有句子。

我认为正则表达式可能是一种方式,但不确定。有什么建议吗?

标签: python

解决方案


只需使用re.DOTALLflag 提取引号内的数据以像任何其他字符一样考虑 endline,并使用“非贪婪”模式

t = """"Going to school.
Taking a few courses and playing basketball.
Got a new puppy."
"Going to school.
I bought a new backpack yesterday.
Got a new cat.
I did my homework as well."
"Going to school.
Brought lunch today." """

import re

print(re.findall('".*?"',t,flags=re.DOTALL))

在引号内打印提取的句子列表。

['"Going to school.\nTaking a few courses and playing basketball.\nGot a new puppy."',
'"Going to school.\nI bought a new backpack yesterday.\nGot a new cat.\nI did my homework as well."',
'"Going to school.\nBrought lunch today."']

现在我们正确地提取了数据,用换行符加入字符串列表并用空格替换内部换行符现在很容易:

print("\n".join([x.replace("\n"," ") for x in re.findall('".*?"',t,flags=re.DOTALL)]))

输出:

"Going to school. Taking a few courses and playing basketball. Got a new puppy."
"Going to school. I bought a new backpack yesterday. Got a new cat. I did my homework as well."
"Going to school. Brought lunch today."

推荐阅读