问题
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