使用python 3在一个txt文件中写入3000+ pdf文件时出错

时间:2016-05-06 21:33:42

标签: python text pypdf2

我试图在一个txt文件中从3000多个PDF中提取文本(而我必须从每个页面中删除标题):

for x in range(len(files)-len(files)+15):
    pdfFileObj=open(files[x],'rb')
    pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
    for pageNum in range(1,pdfReader.numPages):
        pageObj=pdfReader.getPage(pageNum)
        content=pageObj.extractText()
        removeIndex = content.find('information.') + len('information.')
        newContent=content[removeIndex:]
        file.write(newContent)
file.close()

但是,我收到以下错误:

return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\ufb02' in position 5217: character maps to <undefined>

1 个答案:

答案 0 :(得分:0)

我无法检查每个PDF的编码,因此我只使用了replace()。以下是工作代码:

for x in range(len(files)):
    pdfFileObj=open(os.path.join(filepath,files[x]),'rb')
    for pageNum in range(1,pdfReader.numPages):
        pageObj=pdfReader.getPage(pageNum)
        content=pageObj.extractText()
        removeIndex = content.find('information.') + len('information.')
        newContent=content[removeIndex:]
        newContent=newContent.replace('\n',' ')
        newContent=newContent.replace('\ufb02','FL')
        file.write(str(newContent.encode('utf-8')))
file.close()