无法读取pdf文件

2024-06-07 03:16:01 发布

您现在位置:Python中文网/ 问答频道 /正文

text= textract.process("/Users/dg/Downloads/Data Wrangling/syllabi/82445.pdf") 

我试图读取此文件,但它引发以下错误:-

'charmap' codec can't decode byte 0x9d in position 6583: character maps to

为什么会抛出这个错误?我该如何解决这个问题


Tags: 文件textdatapdfdownloads错误processcan
3条回答

这是一个编码问题

Textract使用chardet来检测pdf文件的编码(utf-8、latin1、cp1252等)。检测文件的编码并不总是一件容易的任务,而且chardet可能无法检测文件的编码。在您的情况下,对于这个特定的pdf文件,它似乎失败了

如果您知道文件的编码,那么可以使用如下input_encoding参数:

textract.process(filename, input_encoding="cp1252", output_encoding="utf8")

(见下面链接中的第309期)

注意encoding参数指定的是输出编码,而不是输入编码。 那么,写作

text = textract.process(filename, encoding='ascii')

表示您希望使用ascii编码写入输出文件。但这并不意味着ascii是输入文件的编码

关于chardet的说明: 您可以用chardet猜出这样一个文件的编码:

import chardet
guessed_encoding = chardet.detect(file)
print(guessed_encoding)

它将输出如下内容:

{'encoding': 'EUC-JP', 'confidence': 0.99}

或:

{'encoding': 'EUC-JP', 'confidence': 0.24}

在这里你可以看到有一个confidence键。在第一个示例中,chardet非常确信编码是EUC-JP,但在第二个示例中并非如此

您可以尝试将chardet与导致问题的pdf文件一起使用,并查看其置信度得分

有用链接:

https://github.com/deanmalmgren/textract/issues/309

https://github.com/deanmalmgren/textract/issues/164

关于您的问题,可以通过以下操作解决此错误:

您可以通过两种方式完成:

第一个:是通过执行:r“THEPATH”,它将读取您通过路径插入的文件,例如:text=r“/Users/dg/Downloads/Data Wrangling/sylleti/82445.pdf”

或者你可以加上双“/”,比如://Users//dg//Downloads//Data-Wrangling//提纲//82445.pdf”(这将以同样的方式工作

希望这对您有所帮助:),并随时提出任何进一步的问题

我可以这样做:

import os

file = open("/Users/dg/Downloads/Data Wrangling/syllabi/82445.pdf", "r")
text = file.read()
file.close

相关问题 更多 >