如何解决在 Python 中的某个符号后获取段落
我是 Python 初学者。
我有一个很大的txt文件,格式如下,由许多单句段落组成:
Lorem ipsum dolor sit amet,consectetur adipiscing elit.
****
Sed id placerat magna.
*******
Pellentesque in ex ac urna tincidunt tristique.
Etiam dapibus faucibus gravida.
我试图将输出作为仅在星号段落之后的段落 [每个星号段落最少 4 个星号]。
我需要的输出:
Sed id placerat magna.
Pellentesque in ex ac urna tincidunt tristique.
我正在尝试这样的事情,但我不知道 A] 如何设置每个 星号段落 的最少 4 个星号和 B] 如何设置星号段落之后的段落。
import re
article_content = [open('text.txt').read() ]
after_asterisk_article_paragraph = []
string = "****"
after_asterisk_article_paragraph = string[string.find("****")+4:]
print(*after_asterisk_article_paragraph,sep='\n\n')
再说一次,我刚刚开始使用 Python,请原谅。
解决方法
您可以阅读整个文件并使用一个模式来匹配至少 4 次星号,然后是所有非空行或以 4 次星号开头的行。
^\*{4,}((?:\r?\n(?!\s*$|\*{4}).+)*)
-
^\*{4,}
从字符串的开头匹配 4 次或更多次*
-
(
捕获组 1-
(?:
非捕获组-
\r?\n
匹配换行符 -
(?!\s*$|\*{4}).+
如果整行不为空或以 4 次开头*
使用负前瞻(?!
-
-
)*
(可选)重复该组
-
-
)
关闭捕获组 1
例如使用 re.findall 将返回捕获组 1 值:
import re
file = open('text.txt',mode='r')
result = [s.strip() for s in re.findall(r'^\*{4,}((?:\r?\n(?!\s*$|\*{4}).+)*)',file.read(),re.MULTILINE)]
print(result)
file.close()
输出
['Sed id placerat magna.','Pellentesque in ex ac urna tincidunt tristique.']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。