- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我需要抓取一些 PDF 文件以提取以下文本信息:
我尝试使用 pdfquery 来做到这一点,方法是处理我在 Reddit 上找到的一个示例(参见第一篇文章):https://www.reddit.com/r/Python/comments/4bnjha/scraping_pdf_files_with_python/
我想通过获取许可证号来测试它。我进入生成的“xmltree”文件,找到第一个许可证号并在 LTTextLineHorizontal 元素中获得 x0、y0、x1、y1 坐标。
import pdfquery
from lxml import etree
PDF_FILE = 'C:\\TEMP\\ad-4070-20-september-2018.pdf'
pdf = pdfquery.PDFQuery(PDF_FILE)
pdf.load(4,5)
with open('xmltree.xml','wb') as f:
f.write(etree.tostring(pdf.tree, pretty_print=True))
product_info = []
page_count = len(pdf._pages)
for pg in range(page_count):
data = pdf.extract([
('with_parent', 'LTPage[pageid="{}"]'.format(pg+1)),
('with_formatter', None),
('product_name', 'LTTextLineHorizontal:in_bbox("89.904, 757.502, 265.7, 770.83")'),
('product_details', 'LTTextLineHorizontal:in_bbox("223, 100, 737, 1114")'),
])
for ix, pn in enumerate(sorted([d for d in data['product_name'] if d.text.strip()], key=lambda x: x.get('y0'), reverse=True)):
product_info.append({'Manufacturer': pn.text.strip(), 'page': pg, 'y_start': float(pn.get('y1')), 'y_end': float(pn.get('y1'))-150})
# if this is not the first product on the page, update the previous product's y_end with a
# value slightly greater than this product's y coordinate start
if ix > 0:
product_info[-2]['y_end'] = float(pn.get('y0'))
# for every product found on this page, find the detail information that falls between the
# y coordinates belonging to the product
for product in [p for p in product_info if p['page'] == pg]:
details = []
for d in sorted([d for d in data['product_details'] if d.text.strip()], key=lambda x: x.get('y0'), reverse=True):
if product['y_start'] > float(d.get('y0')) > product['y_end']:
details.append(d.text.strip())
product['Details'] = ' '.join(details)
pdf.file.close()
for p in product_info:
print('Manufacturer: {}\r\nDetail Info:{}...\r\n\r\n'.format(p['Manufacturer'], p['Details'][0:100]))
但是,当我运行它时,它没有打印任何内容。没有错误,XML 文件生成正常,我直接从 XML 文件中获取坐标,所以应该没有问题。我做错了什么?
最佳答案
要从 PDF 文件中提取文本,我最喜欢的工具是 pdftotext
。
使用 -layout
选项,您基本上可以得到纯文本,使用 Python 操作起来相对容易。
示例如下:
"""Extract text from PDF files.
Requires pdftotext from the poppler utilities.
On unix/linux install them using your favorite package manager.
Binaries for ms-windows can be found at;
1) VERY OLD 32 bit http://blog.alivate.com.au/poppler-windows/
RECENT 64 bit https://github.com/oschwartz10612/poppler-windows
2) https://sourceforge.net/projects/poppler-win32/
"""
import subprocess
def pdftotext(pdf, page=None):
"""Retrieve all text from a PDF file.
Arguments:
pdf Path of the file to read.
page: Number of the page to read. If None, read all the pages.
Returns:
A list of lines of text.
"""
if page is None:
args = ['pdftotext', '-layout', '-q', pdf, '-']
else:
args = ['pdftotext', '-f', str(page), '-l', str(page), '-layout',
'-q', pdf, '-']
try:
txt = subprocess.check_output(args, universal_newlines=True)
lines = txt.splitlines()
except subprocess.CalledProcessError:
lines = []
return lines
关于python - 使用 Python 抓取 PDF 文本 (pdfquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52683133/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!