我使用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字符串:我该如何避免它?
答案 0 :(得分:0)
首先,除非有一个微不足道的错误,
.txt写入在返回函数之后发生:永远不执行txt文件写入!
然后,要禁止输出到控制台,只需在运行例程之前执行此操作:
import sys,os
oldstdout = sys.stdout # save to be able to restore it later
sys.stdout = os.devnull