Finding regex in PDF with PDFminer (python) not working

这一生的挚爱 提交于 2020-04-16 02:54:01

问题


I'm trying to find occurrences of a regular expression in a short pdf. However, it doesn't work. I don't understand why, because if I try to search a simple string I don't have problems. The text is rendered correctly. Here is my code:

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
import re

def convert_pdf_to_txt(path):
    #\[\s*prima(?!\S)regex = re.compile(r"\[(\s)prima(?!\S)")

    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):

        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    reg = re.compile(r"\[(\s)prima(?!\S)")
    matches = re.findall(reg, text)
    return matches


print(convert_pdf_to_txt("fel_split.pdf"))

This is my regex: (r"\[(\s)prima(?!\S)") I want to find "[ prima ".


回答1:


Maybe there are more than one space char? Try this: r"\]\s*prima\b"

UPD: and as it appears from the sample document another bracket should've been used: ] instead of [.



来源:https://stackoverflow.com/questions/60833189/finding-regex-in-pdf-with-pdfminer-python-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!