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

我有一个文档文件,它具有以下结构:


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),但一点运气都没有。


海绵宝宝撒
浏览 157回答 4
4回答

慕斯709654

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

炎炎设计

你可以从这个开始:re.search(r'(?<=This&nbsp;is&nbsp;a&nbsp;fairy&nbsp;tale&nbsp;written&nbsp;by\n).*?(?=\n\s*This&nbsp;story&nbsp;is&nbsp;awesome)',&nbsp;s,&nbsp;re.MULTILINE|re.DOTALL).group(0)并微调这个正则表达式。re.MULTILINE可能会被省略,因为你没有^或$无论如何,但也re.DOTALL需要让.匹配换行符。上面的正则表达式使用向前看和向后看(?<=),(?=)。如果您不喜欢那样,您可以使用括号来代替捕获。

函数式编程

如果您可以从文档文件创建字符串列表,则无需使用正则表达式。只需执行这个简单的程序:fileContent = ['This is a fairy tale written by','John Doe and Mary Smith','Auckland,somewhere','This story is awesome',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Some other things', 'story texts', 'Not Important data',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'This is a fairy tale written by','Kem Cho?','Majama?','This story is awesome', 'Not important data']&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;authorsList = []for i in range(len(fileContent)-3):&nbsp; &nbsp; if fileContent[i] == 'This is a fairy tale written by' and fileContent[i+3] == 'This story is awesome':&nbsp; &nbsp; &nbsp; &nbsp; 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?']]

繁星淼淼

尝试改用它。它应该匹配这两个字符串之间的任何内容。re.search(r'(?<=This&nbsp;is&nbsp;a&nbsp;fairy&nbsp;tale).*?(?=This&nbsp;story&nbsp;is&nbsp;awesome)',text)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python