我正在从PDF中提取数据:
字符串Error位于位置n=4,但我需要从位置n+2 (值247156909 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发布于 2021-02-23 18:42:02
当您找到包含Error的行时,您就知道包含该值的行号是当前行号i加2。
因此,将行号存储在一个变量中,并在迭代时检查当前行号是否等于该编号。如果当前行号是您之前存储的行号,则会得到值:
value_line = None # initialize with a value that is not a valid line number
for i, line in enumerate(text.split('\n')):
if re.match(r"Error\s*:", line):
value_line = i + 2
if i == value_line: # this will happen in a later iteration
print(line) # this is the line containing the value或者,预先收集列表中的所有行。然后,您可以直接从列表中访问所需的行,而不需要不断迭代:
lines = text.split('\n')
for i, line in enumerate(lines):
if re.match(r"Error\s*:", line):
print(lines[i + 2])
break # found the value, can stop iterating当然,您可以不打印包含值的行,而是对其执行其他操作,例如拆分它并将第一项转换为整数。
发布于 2021-02-23 22:16:21
.split('\n')提出的方法不适用于大文件(或无限流)。
因为你会把所有东西都放到内存里。
正确的方法是这样的:
import itertools
def pairwise_with_offset(iterable, offset: int):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
[next(b, None) for _ in range(offset)]
return zip(a, b)你可以在这里找到更多信息:https://stackoverflow.com/a/5434936/8933502
请学会使用正确的方法,即使您的PDF库没有经过优化。因为您很可能会一次又一次地重用相同的方式,但也许在将来,它将来自一个类似文件的对象(或任何可迭代对象)。
发布于 2021-02-23 18:48:33
因为"Lines“是一个列表,所以你可以在列表上搜索并检查项目是否存在,然后你就可以得到count+1项目。
import re
# Using readlines()
file1 = open('file.txt', 'r')
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
count += 1
if "Error" in line:
print(Lines[count+1])https://stackoverflow.com/questions/66331421
复制相似问题