【问题标题】:Python: Text extraction and list comprehensionPython:文本提取和列表理解
【发布时间】:2020-08-12 16:54:15
【问题描述】:

我已使用 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])

但我不确定什么条件可以捕获所有“展览”、“X”和“Y”。

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

非常感谢, 伙计

【问题讨论】:

  • 你能提供一些 pdfplumber 输出的样例吗?
  • 嗨 - 我已将此添加到主帖中。谢谢

标签: python list list-comprehension text-extraction


【解决方案1】:

试试这个方法:

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.

显然,您可以通过删除句点、分号等来清理输出。

编辑:第三行的解释:

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

【讨论】:

  • 谢谢 - 这工作得很好。您介意解释一下第 3 行是如何运作的吗?
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2011-08-05
  • 2018-10-03
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
相关资源
最近更新 更多