如何使用 Python3 打开和阅读 pdf(原为 .html)文件

How open and read pdf (originally .html) file using Python3

我需要在 python3 中打开此文件:

http://www.arch.gob.ec/index.php/descargas/doc_download/478-historial-de-produccion-nacional-de-crudo-2011.html

这里我要看一下,提取数据表。我已经搜索了几个小时,但似乎没有任何效果。我是 scraping/parsing 的新手,这是我第一次了解 PDF 的文件处理。

感谢大家的帮助!

从互联网上获取 PDF 称为抓取。试图阅读 PDF 以从中获取数据是另一个问题!

有许多可用的实用程序尝试将 PDF 转换为文本 - 并不完全成功。正如 this article 所解释的那样,PDF 文件很好用(看看),但内部结构并不那么优雅。原因是可见文本通常不直接出现在文档中,必须从表格中重建。在某些情况下,PDF 甚至 不包含 文本,而只是文本的图像。

本文包含几种(尝试)将 PDF 转换为文本的工具。有些人在 Python 中有 'wrappers' 来访问它们。有一些模块听起来很有趣,例如 PyPDF(它不会转换为文本),但实际上不是。

aTXT 看起来很适合数据挖掘 - 尚未测试。

如上所述,其中大部分是现有工具(主要是命令行工具)的包装器(或 GUI)。例如。 Linux 中的一个简单工具(适用于您的 PDF!)是 pdftotext(如果您想留在 Python,您可以使用 subprocesscall,甚至 os.system.

在此之后,您将获得一个文本文件,您可以使用基本的 Python 字符串函数或正则表达式或 PyParser.

等复杂的东西更轻松地处理它

找到适合我的方法。

url = 'http://www.arch.gob.ec/index.php/descargas/doc_download/478-historial-de-produccion-nacional-de-crudo-2011.html'

(pdfFile, headers) = urllib.request.urlretrieve(url)
print(os.path.abspath(pdfFile))
s = pdf_convert(str(os.path.abspath(pdfFile)))

其中 pdf_convert 是:

def pdf_convert(path):
outtype='txt'
opts={}
# Create file that that can be populated in Desktop
outfile = 'c:\users\yourusername\Desktop\temp2.txt'
outdir = '/'.join(path.split('/')[:-1])
# debug option
debug = 0
# input option
password = ''
pagenos = set()
maxpages = 0
# output option
# ?outfile = None
# ?outtype = None
outdir = None
#layoutmode = 'normal'
codec = 'utf-8'
pageno = 1
scale = 1
showpageno = True
laparams = LAParams()
for (k, v) in opts:
    if k == '-d': debug += 1
    elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )
    elif k == '-m': maxpages = int(v)
    elif k == '-P': password = v
    elif k == '-o': outfile = v
    elif k == '-n': laparams = None
    elif k == '-A': laparams.all_texts = True
    elif k == '-V': laparams.detect_vertical = True
    elif k == '-M': laparams.char_margin = float(v)
    elif k == '-L': laparams.line_margin = float(v)
    elif k == '-W': laparams.word_margin = float(v)
    elif k == '-F': laparams.boxes_flow = float(v)
    elif k == '-Y': layoutmode = v
    elif k == '-O': outdir = v
    elif k == '-t': outtype = v
    elif k == '-c': codec = v
    elif k == '-s': scale = float(v)
#
#PDFDocument.debug = debug
#PDFParser.debug = debug
CMapDB.debug = debug
PDFResourceManager.debug = debug
PDFPageInterpreter.debug = debug
PDFDevice.debug = debug
#
rsrcmgr = PDFResourceManager()

outtype = 'text'

if outfile:
    outfp = open(outfile, 'w')

else:
    outfp = sys.stdout
device = TextConverter(rsrcmgr, outfp, laparams=laparams)


fp = open(path, 'rb')
process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password,
                check_extractable=True)
fp.close()
device.close()
outfp.close()
with open ('c:\users\studma~1\Desktop\temp2.txt', 'r') as myfile:
    data = myfile.read()
myfile.close()
return str(data)