Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python为PDF的每个页面循环脚本_Python_Loops_Pdf - Fatal编程技术网

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

使用python为PDF的每个页面循环脚本,python,loops,pdf,Python,Loops,Pdf,刚刚开始学习python,以便在工作中自动完成一项特定而繁琐的任务。也许有人能帮上忙 因此,我正在阅读一个带有pdfplumber的多页PDF文件。数据在每页上以相同的方式排列文本数据。根据这些数据,我需要将一个数据(类型)与另一个数据(大小)进行比较。它工作正常,但我需要手动更改页码。我希望为每一页循环脚本,并列出结果,我不知道如何做到这一点 下面是我的代码示例: `import pdfplumber with pdfplumber.open("typesize.pdf"

刚刚开始学习python,以便在工作中自动完成一项特定而繁琐的任务。也许有人能帮上忙

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

下面是我的代码示例:

`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}")
                

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

感谢您的评论和提示。因此,我的代码应该通过从每个页面提取两组数据并相互比较来发现PDF中的错误。例如,如果变量“Type”的值为“X”,那么页面上另一个变量“Size”的值必须为“1”,否则数据中就有错误。