python - 是否可以在 pdfquery 中使用正则表达式?

标签 python regex pdfminer

我们能否使用正则表达式检测 pdf 中的文本(使用 pdfquery 或其他工具)?

我知道我们可以做到:

pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")
pdf.load()
label = pdf.pq('LTTextLineHorizontal:contains("Cash")')
left_corner = float(label.attr('x0'))
bottom_corner = float(label.attr('y0'))
cash = pdf.pq('LTTextLineHorizontal:in_bbox("%s, %s, %s, %s")' % \
        (left_corner, bottom_corner-30, \
        left_corner+150, bottom_corner)).text()
print cash
'179,000.00'

但是我们需要这样的东西:

pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")
pdf.load()
label = pdf.pq('LTTextLineHorizontal:regex("\d{1,3}(?:,\d{3})*(?:\.\d{2})?")')
cash = str(label.attr('x0'))
print cash
'179,000.00'

最佳答案

这不完全是对正则表达式的查找,但它可以格式化/过滤可能的提取:

def regex_function(pattern, match):
    re_obj = re.search(pattern, match)
    if re_obj != None and len(re_obj.groups()) > 0:
        return re_obj.group(1)
    return None

pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")

pattern = ''
pdf.extract( [
('with_parent','LTPage[pageid=1]'),
('with_formatter', 'text'),
('year', 'LTTextLineHorizontal:contains("Form 1040A (")', 
        lambda match: regex_function(SOME_PATTERN_HERE, match)))
 ])

我没有测试下一个,但它也可能有效:

def some_regex_function_feature():
    # here you could use some regex.
    return float(this.get('width',0)) * float(this.get('height',0)) > 40000

pdf.pq('LTPage[page_index="1"] *').filter(regex_function_filter_here)
[<LTTextBoxHorizontal>, <LTRect>, <LTRect>]

关于python - 是否可以在 pdfquery 中使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33111504/

相关文章:

python - 使用pdfminer水平读取pdf文件

python - 使用 keras ImageGenerator 训练多输入模型

python - 使用时间模块测试复杂性

java - codingBat plusOut 使用正则表达式

regex - 剥离选择查询字符串属性/值对,以便 Varnish 不会因它们而改变缓存

python - 解析 PDF 时忽略表格

python-3.x - XMLConverter 中的意外关键字参数 'codec'

python - 从python中的父类(super class)获取属性

python - f-string,多种格式说明符

visual-studio - 如何使用正则表达式否定字符串