Python:文本提取和列表理解

问题描述

我已经使用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','C400.','The','1,000','luckiest','break','had','the','under','dome','R9.','P21','as','well.','0.1','have','not','found','it','again.','CB12','district','office','see','MM42.']

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

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

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

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

非常感谢, 盖伊

解决方法

尝试一下:

editPost(match.params.userId,match.params.id,token).then((data) => {

输出:

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))。然后,使用这个新的索引位置,找出列表中该位置的哪个元素(index(item)-1]}。如果该前一个元素由单词ap_lst[ap_lst.index(item)-1]组成,则您知道当前元素是目标展览编号。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...