如何在文本文件中搜索一个新行字符并打印它后面的几行?

2024-05-19 22:26:23 发布

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

我有一个文本文件,比如说文本.txt它有以下信息

uncle sam
 work - xyz abc
uncle andrew
 work - xyz abc
aunt michelle 
 work - abcd wxy
aunt rosy 
 work - asdff   

问题:搜索单词“叔叔”,然后使用python的正则表达式打印其相应的工作。在

输出:

^{pr2}$

我是python编程新手,所以任何帮助都是非常感谢的。 谢谢!在


Tags: 文本txt信息samworkabc文本文件abcd
1条回答
网友
1楼 · 发布于 2024-05-19 22:26:23

使用这个简单的正则表达式:

^uncle.*[\r\n]+.*

这样使用:

^{pr2}$

逐字解释:

(?m)                     # ^ matches at the beginning of every line
^                        # the beginning of the string
uncle                    # 'uncle'
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))
[\r\n]+                  # any character of: '\r' (carriage return),
                         # '\n' (newline) (1 or more times (matching
                         # the most amount possible))
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))

相关问题 更多 >