2017-05-21 4 views
-2

기본적으로 가지고 싶은 것은 행 헤더 아래에있는 PDF 데이터 또는 PDF 파일에서 데이터베이스를 만들고 싶습니다. 각 PDF는 25 개로 구성됩니다. 유권자 수에 따라 40 페이지.pdf 텍스트를 추출하고 행 헤더 아래 표를 작성하는 가장 좋은 언어

A page of pdf file I am talking about

나는 상자에서 데이터를 추출 할 (또는 당신이 그들을 무엇을 말) 각 상자에서

이름 이름 열

관계 아래에 표시되도록 액세스/엑셀/SQL로 관계 열 아래에 다른 데이터와 함께 나타납니다.

그러나이 작업을 수행하기 위해 어떤 프로그래밍 언어를 배워야하는지는 잘 모르겠습니다. PDFminer에 대한 검색을 시도했지만 가능할 지 확신 할 수 없습니다. 이 작업을 수행할지 여부. 당신이 어떤 제안이 있다면

, 내가 내가 PDF 파일을 읽고 그들로부터 어떤 데이터를 추출하는 데 필요한 대학 작업을 완료했습니다

+0

pdf 파일의 출처에서 엿볼만한 가치가있을 수 있습니다. 프로그래밍 방식으로 작성된 경우 (거의 확실하게) 페이지 소스가 파싱 할 수있는 규칙적인 방식으로 배치됩니다. 즉 .pdf로 취급하지 말고 구조화 된 텍스트 파일로 취급하십시오. –

+0

... acrobat 대신 텍스트 편집기를 사용하여 .pdf 파일을 엽니 다. 샘플 파일을 나에게 이메일로 보낼 수 있습니까? –

+0

완료했습니다. –

답변

1

,하지만 작동합니다

import csv # spreadsheet output 
import re  # pattern matching 
import sys # command-line arguments 
import zlib # decompression 

# find deflated sections 
PARENT = b"FlateDecode" 
PARENTLEN = len(PARENT) 
START = b"stream\r\n" 
STARTLEN = len(START) 
END = b"\r\nendstream" 
ENDLEN = len(END) 

# find output text in PostScript Tj and TJ fields 
PS_TEXT = re.compile(r"(?<!\\)\((.*?)(?<!\\)\)") 

# return desired per-person records 
RECORD = re.compile(r"Name : (.*?)Relation : (.*?)Address : (.*?)Age : (\d+)\s+Sex : (\w?)\s+(\d+)", re.DOTALL) 

def get_streams(byte_data): 
    streams = [] 
    start_at = 0 
    while True: 
     # find block containing compressed data 
     p = byte_data.find(PARENT, start_at) 
     if p == -1: 
      # no more streams 
      break 
     # find start of data 
     s = byte_data.find(START, p + PARENTLEN) 
     if s == -1: 
      raise ValueError("Found parent at {} bytes with no start".format(p)) 
     # find end of data 
     e = byte_data.find(END, s + STARTLEN) 
     if e == -1: 
      raise ValueError("Found start at {} bytes but no end".format(s)) 
     # unpack compressed data 
     block = byte_data[s + STARTLEN:e] 
     unc = zlib.decompress(block) 
     streams.append(unc) 
     start_at = e + ENDLEN 
    return streams 

def depostscript(text): 
    out = [] 
    for line in text.splitlines(): 
     if line.endswith(" Tj"): 
      # new output line 
      s = "".join(PS_TEXT.findall(line)) 
      out.append(s) 
     elif line.endswith(" TJ"): 
      # continued output line 
      s = "".join(PS_TEXT.findall(line)) 
      out[-1] += s 
    return "\n".join(out) 

def main(in_pdf, out_csv): 
    # load .pdf file into memory 
    with open(in_pdf, "rb") as f: 
     pdf = f.read() 

    # get content of all compressed streams 
    # NB: sample file results in 32 streams 
    streams = get_streams(pdf)  

    # we only want the streams which contain text data 
    # NB: sample file results in 22 text streams 
    text_streams = [] 
    for stream in streams: 
     try: 
      text = stream.decode() 
      text_streams.append(text) 
     except UnicodeDecodeError: 
      pass 

    # of the remaining blocks, we only want those containing the text '(Relation : ' 
    # NB: sample file results in 4 streams 
    text_streams = [t for t in text_streams if '(Relation : ' in t] 

    # consolidate target text 
    # NB: sample file results in 886 lines of text 
    text = "\n".join(depostscript(ts) for ts in text_streams) 

    # pull desired data from text 
    records = [] 
    for name,relation,address,age,sex,num in RECORD.findall(text): 
     name = name.strip() 
     relation = relation.strip() 
     t = address.strip().splitlines() 
     code = t[-1] 
     address = " ".join(t[:-1]) 
     age = int(age) 
     sex = sex.strip() 
     num = int(num) 
     records.append((num, code, name, relation, address, age, sex)) 

    # save results as csv 
    with open(out_csv, "w", newline='') as outf: 
     wr = csv.writer(outf) 
     wr.writerows(records) 

if __name__ == "__main__": 
    if len(sys.argv) < 3: 
     print("Usage: python {} input.pdf output.csv".format(__name__)) 
    else: 
     main(sys.argv[1], sys.argv[2]) 

python myscript.py voters.pdf voters.csv 

같은 명령 줄에서 실행하면이

enter image description here 같은 .CSV 스프레드 시트를 생산

0

을 알려 주시기 바랍니다. 나는 당시 PyPDF2를 사용했다. 데이터를 추출 할 때 문자 인코딩과 자바를 사용하는 사람들 (사용하는 라이브러리를 말할 수 없다)에 많은 문제점이 있습니다. 이런 종류의 문제는 없었습니다.

내 충고는 PytoPDF2가 아닌 Java 또는 다른 'pypdf'라이브러리를 사용해 보시기 바랍니다.

'string'데이터를 처리 할 때는 파이썬이 최선의 선택이라고 생각합니다.

한 가지 더 생각해 봐야 할 것 같습니다. 프로그래밍 경험이 부족하다면 파이썬은 시작하기에 훌륭한 언어입니다. 자바는 다소 무서워합니다. 훨씬 더 내가 생각했던 것보다에 대한 일 처리

0

PyMuPDF은 상당히 쉽습니다. http://ceodelhi.gov.in/WriteReadData/AssemblyConstituency4/AC13/AC0130022.pdf에서 처리하려는 페이지와 비슷한 페이지를 가져 와서이 라이브러리를 다음과 같은 방법으로 적용하여 BeautifulSoup 또는 lxml과 쉽게 구문 분석 할 수있는 HTML을 가져 왔습니다.

>>> import fitz 
>>> doc = fitz.open('AC0130022.pdf') 
>>> page = doc.loadPage(3) 
>>> text = page.getText(output='html') 
>>> len(text) 
52807 
>>> open('page3.html','w').write(text) 
52807 

https://pythonhosted.org/PyMuPDF/tutorial.html에서 PyMuPDF위한 튜토리얼이있다.

관련 문제