我使用 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 字符串:我怎样才能避免它?