0

我使用 pdfminer 将复杂(表格、数字)和非常长的 pdf 转换为 html。我想进一步解析结果(例如提取表格、段落等),然后使用 nltk 中的句子标记器进行进一步分析。为此,我想将 html 保存到文本文件以弄清楚如何进行解析。不幸的是,我的代码没有将 html 写入 txt:

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


def convert_pdf_to_html(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = HTMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0 #is for all
    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)
    fp.close()
    device.close()
    str1 = retstr.getvalue()
    retstr.close()
    return str1
    with open("D:/my_new_file.txt", "wb") as fh:
        fh.write(str1) 

此外,代码在 shell 中打印了整个 html 字符串:我怎样才能避免它?

4

1 回答 1

0

首先,除非有一个微不足道的错误,

.txt 写入发生在返回函数之后:永远不会执行 txt 文件写入!

然后,要抑制输出到控制台,只需在运行例程之前执行此操作:

 import sys,os
 oldstdout = sys.stdout  # save to be able to restore it later
 sys.stdout = os.devnull 
于 2016-07-22T14:02:37.837 回答