【发布时间】:2017-08-29 18:32:05
【问题描述】:
背景
我正在使用 pdfquery 从 pdf 中删除数据。喜欢this one。这个问题建立在我之前的问题here。
我已经成功地使用了可以接受参数as seen in this answer 的自定义包装函数。除了以下当我尝试在 jupyter notebook 中多次运行时给我带来麻烦的问题;
单元格 1
import pdfquery
def load_file(PDF_FILE):
pdf = pdfquery.PDFQuery(PDF_FILE)
pdf.load()
return pdf
file_with_table = 'path_to_the_file_mentioned_above.pdf'
pdf = load_file(file_with_table)
单元格 2
def in_range(prop, bounds):
def wrapped(*args, **kwargs):
n = float(this.get(prop, 0))
return bounds[0] <= n <= bounds[1]
return wrapped
def is_element(element_type):
def wrapped(*args, **kwargs):
return this.tag in element_type
return wrapped
def str_len(condition):
def wrapped(*args, **kwargs):
cond = ''.join([str(len(this.text)),condition])
return eval(cond)
return wrapped
单元格 3
x_check = in_range('x0', (97, 160))
y_check = in_range('y0', (250, 450))
el_check = is_element(['LTTextLineHorizontal', 'LTTextBoxHorizontal'])
str_len = str_len('>0')
els = pdf.pq('LTPage[page_index="0"] *').filter(el_check)
els = els.filter(str_len)
els = els.filter(x_check)
els = els.filter(y_check)
[(i.text) for i in els]
函数str_len,如果在定义后运行一次就可以正常工作;
运行图中第三个单元格时没有错误
但是当我第二次尝试运行该函数时会抛出NameError;
NameError 第二次运行第三个单元后。
这是NameError的文字
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-27-54cd329bb1e1> in <module>()
2 y_check = in_range('y0', (250, 450))
3 el_check = is_element(['LTTextLineHorizontal', 'LTTextBoxHorizontal'])
----> 4 str_len = str_len('>0')
5
6 els = pdf.pq('LTPage[page_index="0"] *').filter(el_check)
<ipython-input-25-654bff7d0eed> in wrapped(*args, **kwargs)
12 def str_len(condition):
13 def wrapped(*args, **kwargs):
---> 14 return eval(''.join([str(len(this.text)),condition]))
15 return wrapped
NameError: name 'this' is not defined
问题
为什么这个函数定义后只能使用一次?
有没有办法绕过这个问题?
【问题讨论】:
-
你这里真的需要同名吗,你不能把左边的名字改成不同的,以后用这个新名字吗? str_len = str_len('>0')
标签: python python-3.x jupyter-notebook wrapper pdf-parsing