2014-10-22 3 views
1

파이썬을 사용하여 pdf에서 텍스트를 추출하려고합니다. 내 프로그램에서이 기능을 사용하려면 때문에이 파이썬 메서드를 stdout에 쓰는 대신 문자열을 반환하는 방법은 무엇입니까?

kramer65 $ pdf2txt.py myfile.pdf 
all the text contents 
of the pdf 
are printed out here.. 

, 나는 명령 줄이 아닌 모듈로 사용하려면 다음과 같이이를 위해 나는 pdf2txt.py command line tool를 사용하여 상당히 좋은 일을 pdfminer를 발견 수단. 다음과 같이

#!/usr/bin/env python 
import sys 
from pdfminer.pdfdocument import PDFDocument 
from pdfminer.pdfparser import PDFParser 
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter 
from pdfminer.pdfpage import PDFPage 
from pdfminer.converter import TextConverter 
from pdfminer.cmapdb import CMapDB 
from pdfminer.layout import LAParams 

def main(fp): 
    debug = 0 
    pagenos = set() 
    maxpages = 0 
    imagewriter = None 
    codec = 'utf-8' 
    caching = True 
    laparams = LAParams() 

    PDFDocument.debug = debug 
    PDFParser.debug = debug 
    CMapDB.debug = debug 
    PDFPageInterpreter.debug = debug 

    resourceManager = PDFResourceManager(caching=caching) 
    outfp = sys.stdout 
    device = TextConverter(resourceManager, outfp, codec=codec, laparams=laparams, imagewriter=imagewriter) 
    interpreter = PDFPageInterpreter(resourceManager, device) 
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, caching=caching, check_extractable=True): 
     interpreter.process_page(page) 
    fp.close() 
    device.close() 
    outfp.close() 
    return # Here I want to return the extracted text string 

지금 모듈로 호출 할 수 있습니다 : 그래서 다음에 pdf2txt.py 파일 조정 관리

>>> from my_pdf2txt import main 
>>> main(open('myfile.pdf', 'rb')) 
all the text contents 
of the pdf 
are printed out here.. 

을 그것은 현재 sys.stdout.write()를 사용하여 결과 문자열을 출력을하지만, 사실은 내 코드의 마지막 줄에있는 return 문을 사용하여 문자열을 반환하기를 원합니다. 그러나 그 sys.stdout.write의 사용은 lines 165-167 in converter.py에 깊이 숨겨져 있기 때문에, 나는 stdout에 쓰는 대신에이 문자열을 반환하는 방법을 알지 못합니다.

누구나 어떻게이 방법을 사용하여 stdout에 쓰지 않고 발견 된 문자열을 반환 할 수 있는지 알 수 있습니까? 모든 팁을 환영합니다!

+1

'file' 또는'StringIO'를'stdout'으로 사용할 수 있습니다. 결과를 잡아 돌려 줄 수 있습니다. –

답변

1

Darth Kotik의 제안에 따라 sys.stdout을 원하는 파일과 같은 객체로 지정할 수 있습니다. 그런 다음 함수를 호출하면 인쇄 된 데이터가 화면이 아닌 객체로 이동합니다. 예 :

import sys 
import StringIO 

def frob(): 
    sys.stdout.write("Hello, how are you doing?") 


#we want to call frob, storing its output in a temporary buffer. 

#hold on to the old reference to stdout so we can restore it later. 
old_stdout = sys.stdout 

#create a temporary buffer object, and assign it to stdout 
output_buffer = StringIO.StringIO() 
sys.stdout = output_buffer 

frob() 

#retrieve the result. 
result = output_buffer.getvalue() 

#restore the old value of stdout. 
sys.stdout = old_stdout 

print "This is the result of frob: ", result 

출력 :

문제에 대한
This is the result of frob: Hello, how are you doing? 

, 당신은 단지 main(fp)으로 frob() 전화를 대체 할 것이다.

+1

'sys.stdout = old_stdout' 대신'sys.stdout = sys .__ stdout__'을 사용할 수 있습니다. 나에게 예쁘다. –

관련 문제