Python从文本文件中提取段落:拆分字符串,与多个嵌套分隔符完全匹配

问题描述 投票:-1回答:2

我正在阅读数百个pdf文件来提取摘要。我的策略是:(1)分隔符后abstract(2)读取摘要(3)停止时空白行。这是可以执行此操作的代码:

import re    
raw = ' Some text\n\nABSTRACT\nExtract \nthis text\n\nOther text'
pattern = 'abstract'
abstract = re.split(pattern ,raw, flags=re.IGNORECASE)[1].split("\n\n")[0]
print(abstract)

问题是不同的pdf文件将包含我的分隔符的不同形式,例如abstract:abstract:\nabstract\n,它们都是嵌套的。因此,我试过这样的事情:

    import re    
    raw = ' Some text\n\nAbstract:\n\nExtract \nthis text\n and include 
 abstraction and Abstraction \n\nOther text'
    pattern = 'abstract|abstract:|abstract:\n' 
    abstract = re.split(pattern, raw, flags=re.IGNORECASE)[1].split("\n\n")[0]
    print(abstract)

然而,它不适用于上述例子。此外,此代码不适用于完全匹配。例如,它不会忽略abstractionAbstraction

python regex string text split
2个回答
1
投票

在你想要拆分的模式中,如果一个是另一个的子集,则将它们排序,它将在列表的后面出现

pattern = 'abstract:|abstract'

不要担心分裂中的尾随空格(\n\n\n\n\t),之后使用.strip()来处理它,因为它会从字符串的末尾删除所有类型的空格。

text_after_abstract_header = re.split(pattern, raw, flags=re.IGNORECASE)[1]
abstract = text_after_abstract_header.strip().split('\n\n')

1
投票

你可以尽可能多地为regexp添加细节,在这种情况下,我们可以在abstract之前和之后添加字符

>>> raw=' Some text\n\nABSTRACT:\t\nExtract this text\n adasdd\n\nSome other text'
>>> arr = re.split('(?i)\n{1,2}abstract[:\n\t]+',raw)[1].split('\n\n')
>>> arr
['Extract this text\n adasdd', 'Some other text']
>>> arr[0]
'Extract this text\n adasdd'

(?i)flags=re.IGNORECASE一样 \n{1,2} 1或2个换行符 [:\n\t]+该字符列表1次或更多次。

© www.soinside.com 2019 - 2024. All rights reserved.