2015-08-08 66 views
0

我正在解析顯示多個不同貨物的貨件信息的PDF文件。數據包括地址,商品金額等。我已經成功地拉出了構成每個文件實體的文本字符串。文件在其演示文稿中相對一致,但不便於定位HTML或XML等數據。首先,我試圖拉取一些物品。在文本中,子字符串「TOTAL BOXES:」有多個實例。每一個之後,存在一個整數(所以它看起來是這樣的:「TOTAL BOXES: 3」)使用文本索引從PDF文件中提取特定數據以找到

我的方法,如以下代碼(在底部一路),一直是:

  1. 找到關鍵短語的情況下,「TOTAL BOXES:
  2. 的「TOTAL BOXES:
  3. 使用該子字符串中的最後一個字符的索引每個實例的查找索引 - 在這種情況下,「:」 - 爲「move forward」 2字索引頭寸來拉動數據。

我假設有可能更優雅的解決方案,我很高興聽到他們。但現在我的主要絆腳石與我選擇的方法是:

我能夠返回關鍵短語的每個索引作爲列表中的項目。然後我將2添加到該索引以獲得「後端」索引。我現在知道文本中提供目標數據的確切索引或每個地方。每個索引都存儲在我的變量instance_begin下的列表項中。

這是我的代碼崩潰,我的新手照亮。在instance_begin

的盒子:在努力獲取數據,我這樣做

box = raw_data[(instance_begin[box]):(instance_end[box])] 

它返回例外:

TypeError: list indices must be integers, not list

幫助表示讚賞。

代碼:

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter 
from pdfminer.converter import TextConverter 
from pdfminer.layout import LAParams 
from pdfminer.pdfpage import PDFPage 
from cStringIO import StringIO 
from re import findall, finditer 

path = "/file.pdf" 

def convert_pdf_to_txt(path): 
    rsrcmgr = PDFResourceManager() 
    retstr = StringIO() 
    codec = 'utf-8' 
    laparams = LAParams() 
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) 
    fp = file(path, 'rb') 
    interpreter = PDFPageInterpreter(rsrcmgr, device) 
    password = "" 
    maxpages = 0 
    caching = True 
    pagenos=set() 

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): 
     interpreter.process_page(page) 

    text = retstr.getvalue() 

    fp.close() 
    device.close() 
    retstr.close() 
    return text 

raw_data = convert_pdf_to_txt(path) 

key_phrase = "TOTAL BOXES:" 

instance_begin = [i.end() for i in re.finditer(key_phrase, raw_data)] 

instance_end = [(i + 2) for i in instance_begin] 

box = raw_data[(instance_begin[box]):(instance_end[box])] 
+0

你說的代碼行不在你的源代碼清單中,所以當然不可能弄清楚你做錯了什麼。錯誤信息告訴你列表索引(只能是變量'box')是一個列表,而不是一個整數。對於這樣的事情,Python總是正確的。 –

+0

我編輯了我的問題以包含非功能性代碼。我知道列表索引必須是一個整數。我的問題是使用列表中的項目(這是一組整數)作爲索引。有什麼想法嗎? – Murcielago

回答

0

讓我總結一下我對你的問題的理解。您有一個長字符串,名稱爲raw_data。你想從這個字符串中切出某些2個字符的序列。這些切片開始的索引存儲在列表instance_begin中。如果這是正確的,這裏是一個單行的解決方案:

box = [raw_data[i:i+2] for i in instance_begin] 

在此聲明box的末尾兩個字符串所需的列表。名單instance_end是沒有必要的。道歉,如果我仍然誤解你的問題。