在表达式的任意组合之间提取文本(列表)

时间:2018-11-05 15:05:24

标签: python regex text-mining text-extraction

我需要从文本文件(嵌入在较大文件中的字母的开头和结尾)中提取两个表达式(开头和结尾)之间的文本。我面临的问题是,字母的开头和结尾都有多种潜在的表达方式。

我有一个表达式列表,有可能作为开始/结束表达式。我需要从较大的文本(包括开始和结束表达式)中提取这些表达式的任何组合之间的所有文本,并将其写入新文件。

sample_text = """Some random text 
asdasd
asdasd
asdasd
**Dear my friend,
this is the text I want to extract.
Sincerly,
David**
some other random text
adasdsasd"""

到目前为止,我的代码:

letter_begin = ["dear", "to our", "estimated", ...]
letter_end = ["sincerly", "yours", "best regards", ...]

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "dear": #shortcomming: only 1 Expression possible here
            copy = True
        elif line.strip() == "sincerly": #shortcomming: only 1 Expression possible here
            copy = False
        elif copy:
            outfile.write(line)

上面的示例包括“ Dear”作为letter_begin表达式和“ Sincerly”作为letter_end表达式。我需要一个灵活的代码,该代码能够捕获上述列表中的任何开头和结尾字母表达式(这些表达式的任何可能组合;例如,“亲爱的问候”或“估计的...”真诚的”)

1 个答案:

答案 0 :(得分:1)

我们可以尝试在{all}和多行模式下以以下模式使用re.findall

Dear\s+.*?Sincerely,\n\S+

这将捕获并包括单词DearSincerely之前的所有内容,然后是Sincerely下一行之后的所有内容。这是一个代码示例:

output = re.findall(r"Dear\s+.*?Sincerely,\n\S+", sample_text, re.MULTILINE|re.DOTALL)
print(output)

编辑:

如果您想匹配多个可能的问候语和结束语,那么我们可以使用一种交替方式:

letter_begin = ["dear", "to our", "estimated"]
openings = '|'.join(letter_begin)
print(openings)
letter_end = ["sincerely", "yours", "best regards"]
closings = '|'.join(letter_end)
regex = r"(?:" + openings + r")\s+.*?" + r"(?:" + closings + r"),\n\S+"
output = re.findall(regex, sample_text, re.MULTILINE|re.DOTALL|re.IGNORECASE)
print(output)

['Dear my friend,\nthis is the text I want to extract.\nSincerely,\nDavid**']