繁体   English   中英

如何获取此Python方法以返回字符串,而不是将其写入stdout?

[英]How to get this Python method to return a string instead of writing it to stdout?

我正在尝试使用Python从pdf中提取文本。 为此,我使用pdf2txt.py命令行工具找到了pdfminer ,它做得相当不错:

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

因为我想在程序中使用此功能,所以我想将其用作模块而不是命令行工具。 所以我设法将pdf2txt.py文件调整为以下内容:

#!/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

我现在可以将其称为模块,如下所示:

>>> 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的使用隐藏在converter.py的第165-167行的深处,所以我真的不知道如何获取此方法以返回这些字符串,而不是将其写入stdout。

有人知道我如何获得此方法以返回找到的字符串,而不是将其写入stdout吗? 欢迎所有提示!

如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()调用即可。

问题是如何以字符串形式返回输出。 如果有人在这里,反而想知道如何将输出直接写到文件中,而不是打印在终端上。 这是为我工作的单线解决方案。

只需添加以下行:

sys.stdout=open("pdf_text.txt","w")

前行:

outfp = sys.stdout.

希望这对某人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM