我需要在 python3 中打开这个文件:
在这里我必须阅读它,并提取数据表。我已经搜索了几个小时,但似乎没有任何效果。我是抓取/解析的新手,这是我第一次研究 PDF 的文件处理。
感谢您的各种帮助!
我需要在 python3 中打开这个文件:
在这里我必须阅读它,并提取数据表。我已经搜索了几个小时,但似乎没有任何效果。我是抓取/解析的新手,这是我第一次研究 PDF 的文件处理。
感谢您的各种帮助!
从 Internet 获取 PDF 称为抓取。尝试阅读 PDF 以从中获取数据是另一个问题!
有许多实用程序可以尝试将 PDF 转换为文本 - 并不完全成功。正如本文所解释的,PDF 文件很好用(看看),但内部却没有那么优雅。原因是可见文本通常不直接存在于文档中,并且必须从表格中重建。在某些情况下,PDF 甚至不包含文本,而只是文本的图像。
这篇文章包含几个工具来(尝试)将 PDF 转换为文本。有些在 Python 中有“包装器”来访问它们。有一些模块听起来很有趣,例如PyPDF(它不会转换为文本),但实际上并非如此。
aTXT看起来对数据挖掘很有趣——还没有测试过。
如上所述,其中大多数是围绕现有工具(主要是命令行工具)的包装器(或 GUI)。例如。Linux 中的一个简单工具(适用于您的 PDF!)是pdftotext
(如果您想留在 Python 中,您可以使用subprocess
'scall
或什至使用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)