Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

python - 'Nonetype object is not itreable' when trying to extract from PDF

I am trying to extract data from a PDF, but I keep getting a type error because my object is not iterable (on the statement for line in text: but I don't understand why 'text' has no value, just above that I create the text object using text = page.extract.text() and then I want to iterate through each line of the text to find matches to my regexes.

I'm afraid that my statement for line in text: is the problem; perhaps using 'line' isn't appropriate, but I don't know what else to do.

My code is below, thanks for looking!

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))
question from:https://stackoverflow.com/questions/65649324/nonetype-object-is-not-itreable-when-trying-to-extract-from-pdf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try setting the loop directly equal to the page.extract_text() value. Like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...