用python为PDF的每一页循环一个脚本



刚刚开始学习python,以便在工作中自动化一项特定而乏味的任务。也许有人可以帮助一个小女孩?:(

所以我正在阅读一个多页的PDF文件与pdfplumber。数据是在每一页上排列相同的文本数据。根据这些数据,我需要将一段数据(类型(与另一段数据的大小进行比较。它工作正常,但我需要手动更改页码。我希望为每一页循环脚本并列出结果,但我不知道如何做到这一点。

下面是我的代码示例:

`import pdfplumber
with pdfplumber.open("typesize.pdf") as pdf:
page = pdf.pages[0]
text = page.extract_text()
print(page)
for row in text.split('n'):
if row.startswith('Type'):
type = row.strip()[-1:]
print("Type", type)
for row in text.split('n'):
if row.startswith('Size'):
size = row.split()[-1]
print("Size", size)
if type == 'X' and size == '1':
print("OK")
elif type == 'Y' and size == '2':
print("OK")
elif type == 'Z' and size == '3':
print("OK")
else: print("INCORRECT")`

这是我得到的结果:

Page:1
Type X
Size 1
OK

我以前从未使用过pdfplumber,但从文档来看,pdfplumber.PDF.pages只是页面对象的列表,因此您应该能够使用简单的for循环对它们进行迭代。我不知道你的代码是做什么的,但我会把它改成下面这样:

import pdfplumber
with pdfplumber.open("typesize.pdf") as pdf:
for page in pdf.pages:
current_page_text = page.extract_text()
for row in current_page_text.splitlines():
if row.startswith("Type"):
special_type = row.strip()[-1:]
print(f"Type: {special_type}")
elif row.startswith("Size"):
size = row.split()[-1]
print(f"Size: {size}")

我已经将您的type变量重命名为special_type,因为type是Python中的保留关键字,您不应该将其用作变量标识符。

最新更新