Python:文本提取和列表理解

Python: Text extraction and list comprehension

我使用 pdfplumber 从 pdf 文件中提取了文本。文本包含几个格式为 'Exhibit XY' 的项目,其中 X 是字母,Y 是数字,例如图表 C40 或图表 R700。

我试图减少整个提取的文本以简单地将各种 Exhibit XY 组合显示为列表。我最初的想法是将文本字符串转换为列表:

import pdfplumber

with pdfplumber.open(file) as pdf:

    p1 = pdf.pages[0]
    p2 = pdf.pages[1]
    p3 = pdf.pages[2]
    
    p1_text = p1.extract_text()
    p2_text = p2.extract_text()
    p3_text = p3.extract_text()
    
    # print(p1_text, p2_text, p3_text)
    
    full_text = p1_text + p2_text + p3_text
    
    list_full_text = full_text.split()

pdfplumber 的输出如下:

apple cars 2014 pizza hut. Aftermath, you tried an Exhibit R40; decidedly 50 times 
larger than Exhibit C400. The 1,000 luckiest break had the under dome Exhibit R9. 
Exhibit P21 as well. 0.1 you have not found it again. Exhibit CB12 district office see 
Exhibit MM42. 

在列表形式中,这是:

['apple', 'cars', '2014', 'pizza', 'hut.', 'Aftermath,', 'you', 'tried', 'an', 'Exhibit', 'R40;', 'decidedly', '50', 'times', 'larger', 'than', 'Exhibit', 'C400.', 'The', '1,000', 'luckiest', 'break', 'had', 'the', 'under', 'dome', 'Exhibit', 'R9.', 'Exhibit', 'P21', 'as', 'well.', '0.1', 'you', 'have', 'not', 'found', 'it', 'again.', 'Exhibit', 'CB12', 'district', 'office', 'see', 'Exhibit', 'MM42.']

我的感觉是某种形式的列表理解可能能够减少列表以仅提供 Exhibit XY 组合,例如像这样:

print([i for i in list_full_text if [some condition])

但我不确定什么条件可以捕获所有 'Exhibit'、'X' 和 'Y'。

注意:正文还包含各种数字,例如年份(例如 1992)或数量(例如 50)。我只需要前面有字母的那些。

非常感谢, 盖伊

这样试试:

ap_lst = [your list above]
for item in ap_lst:
    if 'Exhibit' in ap_lst[ap_lst.index(item)-1]:
        print('Exhibit',item)

输出:

Exhibit R40;
Exhibit C400.
Exhibit R9.
Exhibit P21
Exhibit CB12
Exhibit MM42.

显然,您可以通过删除句点、semi-colons 等来清理输出

编辑:第三行解释:

对于列表中的每个元素,找到该元素的索引位置 (ap_lst.index(item))。现在我们需要检查紧接在前的列表元素中的单词是什么——紧接在前的元素的索引位置比当前元素的索引位置低一个 (index(item)-1])。然后,使用这个新的索引位置,找出列表中该位置的元素 (ap_lst[ap_lst.index(item)-1]}。如果前面的元素由单词 is Exhibit 组成,则您知道当前元素是目标展品编号。