Skip to main content
 首页 » 编程设计

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

2024年12月31日8jirigala

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

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

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) 

上面的示例包括“亲爱的”作为 letter_begin 表达式和“Sincerly”作为 letter_end 表达式。我需要一个灵活的代码,它能够从上面的列表中捕获任何开头和结尾的字母表达式(表达式的任何潜在组合;例如“亲爱的 [...] 再见”或“估计 [...]真诚的)

请您参考如下方法:

我们可以尝试使用re.findall在全点和多行模式下,具有以下模式:

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

这将捕获并包括来自单词 Dear 的所有内容, 包括 Sincerely , 然后是 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**']