【问题标题】:Getting TypeError: ord() expected string of length 1, but int found error获取 TypeError:ord() 预期长度为 1 的字符串,但 int 发现错误
【发布时间】:2019-09-23 10:04:54
【问题描述】:

代码是

from PyPDF2 import PdfFileReader
with open('HTTP_Book.pdf','rb') as file:
    pdf=PdfFileReader(file)
    pagedd=pdf.getPage(0)
    print(pagedd.extractText())

此代码引发如下所示的错误:

TypeError: ord() expected string of length 1, but int found

我在互联网上搜索并找到了这个Troubleshooting "TypeError: ord() expected string of length 1, but int found" 但这并没有多大帮助。我知道这个错误的背景是什么,但不确定它与这里有什么关系?

尝试更改 pdf 文件,它工作正常。那么出了什么问题:pdf文件或PyPDF2无法处理?根据文档,我知道这种方法不太可靠:

这对某些 PDF 文件效果很好,但对其他文件效果不佳,具体取决于所使用的生成器

应该如何处理?

追溯:

Traceback (most recent call last):
  File "pdf_reader.py", line 71, in <module>
    print(pagedd.extractText())
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.py", line 2595, in ex
tractText
    content = ContentStream(content, self.pdf)
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.py", line 2673, in __
init__
    stream = BytesIO(b_(stream.getData()))
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\generic.py", line 841, in
 getData
    decoded._data = filters.decodeStreamData(self)
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\filters.py", line 350, in
 decodeStreamData
    data = LZWDecode.decode(data, stream.get("/DecodeParms"))
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\filters.py", line 255, in
 decode
    return LZWDecode.decoder(data).decode()
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\filters.py", line 228, in
 decode
    cW = self.nextCode();
  File "C:\Users\Jeet\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\filters.py", line 205, in
 nextCode
    nextbits=ord(self.data[self.bytepos])
TypeError: ord() expected string of length 1, but int found

【问题讨论】:

  • 我已将您的问题编辑为独立存在。 SO 是一个问答网站,而不是论坛,所以参考其他问题是可以的,但依靠它们来保持连续性是不行的。我建议的唯一进一步更改是添加指向您的 pdf 文件的链接。

标签: python python-3.x pypdf


【解决方案1】:

我有问题。这只是 PyPDF2 的一个限制。我使用 tika 和 BeautifulSoup 来解析和提取文本,效果很好。虽然它需要更多的工作。

from tika import parser 
from bs4 import BeautifulSoup
raw=parser.from_file('HTTP_Book.pdf',xmlContent=True)['content']
data=BeautifulSoup(raw,'lxml')
message=data.find(class_='page') # for first page
print(message.text)

【讨论】:

  • 虽然这可能是一种有效的解决方法,但我有兴趣找出文件中导致此问题的原因。看起来可能需要向 PyPDF 提交错误报告,并且可能需要修复。
猜你喜欢
  • 2013-11-22
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多