【问题标题】:'Nonetype object is not itreable' when trying to extract from PDF尝试从 PDF 中提取时出现“Nonetype 对象不可迭代”
【发布时间】:2021-01-10 01:27:02
【问题描述】:

我正在尝试从 PDF 中提取数据,但我不断收到类型错误,因为我的对象不可迭代(在声明 for line in text: 但我不明白为什么“文本”没有价值,就在上面我使用text = page.extract.text() 创建了文本对象,然后我想遍历文本的每一行以查找与我的正则表达式匹配的内容。

恐怕我的声明for line in text:是问题所在;或许使用 'line' 不合适,但我不知道还能做什么。

下面是我的代码,谢谢观看!

import requests
import pdfplumber
import pandas as pd
import re
from collections import namedtuple

Line = namedtuple('Line', 'gbloc_name contact_type email')

gbloc_re = re.compile(r'^(?:a\.\s[A-Z]{5}\:\s[A-Z]{4})')

line_re = re.compile(r'^[^@\s]+@[^@\s]\.[^@\s]+$')

file = 'sampleReport.pdf'
  
lines=[]

with pdfplumber.open(file) as pdf:
    pages = pdf.pages 
    for page in pdf.pages: 
        text = page.extract_text() 
        for line in text: 
            gbloc = gbloc_re.search(line) 
            if gbloc:
                gbloc_name = gbloc

            elif line.startswith('Outbound'):
                contact_type = 'Outbound'
            
            elif line.startswith('Tracing'):
                contact_type = 'Tracing'
            
            elif line.startswith('Customer'):
                contact_type = 'Customer Service'

            elif line.startswith('QA'):
                contact_type = 'Quality Assurance'
            
            elif line.startswith('NTS'):
                contact_type = 'NTS'

            elif line.startswith('Inbound'):
                contact_type = 'Inbound'
            
            elif line_re.search(line):
                items = line.split()
                lines.append(Line(gbloc_name, contact_type, *items))

【问题讨论】:

  • 能否分享您的sampleReport。 pdf?

标签: python nonetype pdf-parsing pdf-extraction


【解决方案1】:

尝试将循环直接设置为 page.extract_text() 值。像这样:

with pdfplumber.open(file) as pdf:
    for page in pdf.pages:
        for line in page.extract_text():

【讨论】:

  • 谢谢,但发生了同样的错误。我将代码更改为:lines=[] with pdfplumber.open(file) as pdf: for page in pdf.pages: for line in page.extract_text(): gbloc = gbloc_re.search(line) if gbloc: gbloc_name = gbloc
  • 我可能可以通过一些测试来更新我的答案。请附上您正在使用的 pdf 文件
  • 谢谢!文件在这里:link
  • 错误到底发生在哪里?因为我运行了代码,它对我来说很好
  • 谢谢@DapperDuck,我确实需要'如果不是文本:继续'才能让它工作 - 我不确定为什么没有它对你有用 - 但我非常感谢你的帮助!
【解决方案2】:

我使用 lib PyPDF2 从 PDF 中提取文本。在这里,我做了一个简单的源代码。 它将按页面提取内容。

import PyPDF2

with open('example.pdf', 'rb') as pdfFileObj:
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    print(pdfReader.numPages)
    for i in range(0, pdfReader.numPages):
        print("Page: ", i)
        pageObj = pdfReader.getPage(i)
        print(pageObj.extractText())

图像结果:

如果您有任何问题,请查看并回复我。

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2021-11-26
    • 2017-02-20
    • 2016-02-08
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多