按段落拆分文本

2024-04-23 22:24:24 发布

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

我有这样一个样本文本

 ## Paragraph 1\n\nThe [`sys`](https://docs.python.org/3.6/library/sys.html#module-sys) module also has attributes for *stdin*, *stdout*, and *stderr*. \n\nThe latter is useful for emitting warnings and error messages to make them visible even when *stdout* has been redirected:\n\n## Paragraph 2\n\nThe [`re`](https://docs.python.org/3.6/library/re.html#module-re) module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:\n\nWhen only simple capabilities are needed, string methods are preferred because they are easier to read and debug.

我想用regex而不是str.split将它分成两段,所以我尝试了。在

^{pr2}$

输出我的意图是分开完整的段落。在

['## Paragraph 1\n\nThe [`sys`](https://docs.python.org/3.6/library/sys.html#module-sys) module also has attributes for *stdin*, *stdout*, and *stderr*. \n\nThe latter is useful for emitting warnings and error messages to make them visible even when *stdout* has been redirected:\n\n',
'## Paragraph 2\n\nThe [`re`](https://docs.python.org/3.6/library/re.html#module-re) module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:\n\nWhen only simple capabilities are needed, string methods are preferred because they are easier to read and debug.']

如何实现?在


Tags: andhttpsorgredocsforhtmlstdout
2条回答

您可以尝试内置的分割功能

string = '''I am new to python # please help me '''
data = string.split('#')
print(data)

输出

['I am new to python ', ' please help me ']

你可以试试这个:

import re
s = " ## Paragraph 1\n\nThe [`sys`](https://docs.python.org/3.6/library/sys.html#module-sys) module also has attributes for *stdin*, *stdout*, and *stderr*. \n\nThe latter is useful for emitting warnings and error messages to make them visible even when *stdout* has been redirected:\n\n## Paragraph 2\n\nThe [`re`](https://docs.python.org/3.6/library/re.html#module-re) module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:\n\nWhen only simple capabilities are needed, string methods are preferred because they are easier to read and debug."
paragraphs = re.split('\n(?=## Paragraph \d+)', s)

输出:

^{pr2}$

相关问题 更多 >