为了账号安全,请及时绑定邮箱和手机立即绑定

在 Python 中使用正则表达式在文本后提取字符串

在 Python 中使用正则表达式在文本后提取字符串

海绵宝宝撒 2023-06-13 15:37:07
我有一个文档文件,它具有以下结构:This is a fairy tale written by    John Doe and Mary Smith        Auckland,somewhere     This story is awesome我想提取两行文本,它们是:        John Doe and Mary Smith                Auckland,somewhere并使用正则表达式将这些值附加到列表中。我要提取的两行总是在This is a fairy tale和 所写的行之间This story is awesome。我怎样才能做到这一点?我尝试了一些与 的组合before_keyword,keyword,after_keyword=text.partition(regex),但一点运气都没有。
查看完整描述

4 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

re.DOTALL您可以使用正则表达式来.匹配任何字符,包括换行符。一旦在两个分隔符之间有了文本,就可以使用另一个不带 的正则表达式来re.DOTALL提取至少包含一个非空白字符 ( \S) 的行。


import re


lst = []


with open('input.txt') as f:

    text = f.read()


match = re.search('This is a fairy tale written by(.*?)This story is awesome', 

                  text, re.DOTALL)


if match:

    lst.extend(re.findall('.*\S.*', match.group(1)))


print(lst)

给出:


['    John Doe and Mary Smith', '    Auckland,somewhere']


查看完整回答
反对 回复 2023-06-13
?
炎炎设计

TA贡献1808条经验 获得超4个赞

你可以从这个开始:

re.search(r'(?<=This is a fairy tale written by\n).*?(?=\n\s*This story is awesome)', s, re.MULTILINE|re.DOTALL).group(0)

并微调这个正则表达式。re.MULTILINE可能会被省略,因为你没有^$无论如何,但也re.DOTALL需要让.匹配换行符。上面的正则表达式使用向前看和向后看(?<=)(?=)。如果您不喜欢那样,您可以使用括号来代替捕获。


查看完整回答
反对 回复 2023-06-13
?
函数式编程

TA贡献1807条经验 获得超9个赞

如果您可以从文档文件创建字符串列表,则无需使用正则表达式。只需执行这个简单的程序:


fileContent = ['This is a fairy tale written by','John Doe and Mary Smith','Auckland,somewhere','This story is awesome',

               'Some other things', 'story texts', 'Not Important data',

               'This is a fairy tale written by','Kem Cho?','Majama?','This story is awesome', 'Not important data']

               

authorsList = []

for i in range(len(fileContent)-3):

    if fileContent[i] == 'This is a fairy tale written by' and fileContent[i+3] == 'This story is awesome':

        authorsList.append([fileContent[i+1], fileContent[i+2]])


print(authorsList)

在这里,我只是检查'This is a fairy tale written by'and'This story is awesome'如果找到,则在列表中在它之间添加文本。


输出:


[['John Doe and Mary Smith', 'Auckland,somewhere'], ['Kem Cho?', 'Majama?']]


查看完整回答
反对 回复 2023-06-13
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

尝试改用它。它应该匹配这两个字符串之间的任何内容。

re.search(r'(?<=This is a fairy tale).*?(?=This story is awesome)',text)


查看完整回答
反对 回复 2023-06-13
  • 4 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信