Python 试图从PDF中提取文本时出现以下错误:“引用”;TypeError:只能将str(而不是“NoneType”)连接到str;
我目前正试图从这整本书中提取文本。我曾尝试从PDF的单个页面中提取文本,它工作正常,但当我尝试提取整个PDF时,会出现以下错误:Python 试图从PDF中提取文本时出现以下错误:“引用”;TypeError:只能将str(而不是“NoneType”)连接到str;,python,pdf,pdfplumber,Python,Pdf,Pdfplumber,我目前正试图从这整本书中提取文本。我曾尝试从PDF的单个页面中提取文本,它工作正常,但当我尝试提取整个PDF时,会出现以下错误: Traceback (most recent call last): File "D:/PDF_extract_1/main.py", line 35, in <module> extract_whole_pdf() File "D:/PDF_extract_1/main.py", line
Traceback (most recent call last):
File "D:/PDF_extract_1/main.py", line 35, in <module>
extract_whole_pdf()
File "D:/PDF_extract_1/main.py", line 26, in extract_whole_pdf
final = final + "\n" + data
TypeError: can only concatenate str (not "NoneType") to str
这是我用来提取整个PDF的代码:
def extract_whole_pdf():
pdf = pdfplumber.open("pdftest2.pdf")
n = len(pdf.pages)
final = ""
for page in range(n):
data = pdf.pages[page].extract_text()
final = final + "\n" + data
print("Whole document data : {}".format(final))
with open("pdf_extract.txt", "w", encoding='utf-8') as f:
f.write(final)
pdf.close()
我注意到这个问题被问了很多次,但它们似乎不适用于我的问题。其中一个有一个类似的错误,但情况与我的不同。问题似乎是方法
extract\u text()
在找到空页时返回None
。您可以通过在连接之前测试返回的数据来解决此问题:
def extract_total_pdf():
pdf=pdfplumber.open(“pdftest2.pdf”)
n=len(pdf.pages)
final=“”
对于范围(n)中的页面:
data=pdf.pages[page].extract_text()
如果数据:
final=final+“\n”+数据
打印(f“整个文档数据:{final}”)
将open(“pdf_extract.txt”,“w”,encoding='utf-8')作为f:
f、 写作(期末)
pdf.close()
作为补充说明,我还建议使用f-strings进行字符串格式设置,因为它是最新的标准。
extract\u text()
在某些时候返回None
。仔细检查该方法的文档,看看它指示了什么。我们希望您在文章中包含基本诊断。至少,在错误点打印可疑值,并将其追溯到其来源。在许多情况下,执行此基本诊断将向您显示问题所在,并且您根本不需要堆栈溢出。在这种情况下,您需要跟踪page
的特定值不返回文本的原因。
def extract_whole_pdf():
pdf = pdfplumber.open("pdftest2.pdf")
n = len(pdf.pages)
final = ""
for page in range(n):
data = pdf.pages[page].extract_text()
final = final + "\n" + data
print("Whole document data : {}".format(final))
with open("pdf_extract.txt", "w", encoding='utf-8') as f:
f.write(final)
pdf.close()