我正在使用pdftotext Python库从PDF文档中提取一些数据。
import pdftotext
# Load your PDF
with open("text2.pdf", "rb") as f:
pdf = pdftotext.PDF(f)
# How many pages?
print(len(pdf))
data = "nn".join(pdf)
# Read all the text into one string
print(data)
提取的数据为:
Account Name :Mr. SX
Account Name :Mr. XX XX XX
Address : Address detaisls
Date :7 Sep 2021
Account Number :00000031873583221
Account Description :REGULAR SB CHQ-INDIVIDUALS
Branch :SSI
Drawing Power :0.00
整个数据是字符串,但我想只提取帐户号码。我使用正则表达式:
^(Accounts+Number).*$
但不知道如何从整个字符串中提取数据。
你可以试试:
>>> 'n'.join([re.sub(r'Account Numbers+:', '', line) for line in data.splitlines() if 'Account Number' in line])
'00000031873583221'
>>>
不使用regex更容易:
>>> 'n'.join([line.split(':')[-1] for line in data.splitlines() if 'Account Number' in line])
'00000031873583221'
>>>