我正在从PDF中提取数据:
字符串Error
位于位置n=4
,但我需要从位置n+2
(value247156909 xxxx
)提取值
4 Error:
5 XZXZXZXZXZXZX
6 247156909 xxxx
with pdfplumber.open(file) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
for i, line in enumerate(text.split('\n')):
print(i, line)
elif re.match(r"Error\s*:", line):
tot = line.split() # how can I get line on position i+2
用
.split('\n')
提出的方法在大文件(或无限流)上不起作用因为你会把一切都记在记忆里
正确的方法是:
您可以在此处找到更多信息: https://stackoverflow.com/a/5434936/8933502
请学会使用正确的方法,即使你的PDF库没有优化。因为您可能会一次又一次地重复使用相同的方法,但将来可能会使用类似于文件的对象(或任何iterable)
当您找到包含
Error
的行时,您知道包含该值的行号是当前行号i
加上2因此,将该行号存储在变量中,并在迭代时检查当前行号是否等于该行号。如果当前行号是您以前存储的行号,则会得到以下值:
或者,事先收集列表中的所有行。然后,您可以直接从列表中访问所需的行,无需不断迭代:
当然,不必打印包含该值的行,您可以使用它执行其他操作,例如拆分它并将第一项转换为整数
因为“行”是一个列表,你可以在列表上输入,检查项目是否存在,从这一点你可以得到计数+1项目
相关问题 更多 >
编程相关推荐