Python:特殊字符给我带来问题(来自PDFminer)

时间:2011-07-29 08:00:21

标签: python

我使用PDFminer的pdf2text将PDF缩减为文本。不幸的是它包含特殊字符。让我显示我的控制台的输出

>>>a=pdf_to_text("ap.pdf")

这是一个样本,有点截断

>>>a[5000:5500]
'f one architect. Decades ...... but to re\xef\xac\x82ect\none set of design ideas, than to have one that contains many\ngood but independent and uncoordinated ideas.\n1 Joshua Bloch, \xe2\x80\x9cHow to Design a Good API and Why It Matters\xe2\x80\x9d, G......=-3733'

我明白我必须编码

>>>a[5000:5500].encode('utf-8')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 237: ordinal not in range(128)

我搜索了一下并试了一下,特别是Replace special characters in python。输入来自PDFminer,所以它很难控制(AFAIK)。从这个输出中制作正确明文的方法是什么?

我做错了什么?

- 快速修复:将PDFminer的编解码器更改为ascii-但这不是一个持久的解决方案 -

- 放弃了答案的快速修复 - 更改编解码器会删除信息 -

- Maxim http://en.wikipedia.org/wiki/Windows-1251 -

提及的相关主题

1 个答案:

答案 0 :(得分:10)

当非{ASCII}文本存储在str个对象中时,通常会发生此问题。您要做的是在utf-8中编码已经以某种编码方式编码的字符串(因为它包含代码高于0x7f的字符)。

要在utf-8中对这样的字符串进行编码,必须先对其进行解码。假设原始文本编码为cp1251(将其替换为您的实际编码),类似下面的内容将起到作用:

u = s.decode('cp1251')  # decode from cp1251 byte (str) string to unicode string
s = u.encode('utf-8')   # re-encode unicode string to  utf-8 byte (str) string

基本上,上面的代码片段执行iconv --from-code=CP1251 --to-code=UTF-8命令所做的操作,即它将字符串从一种编码转换为另一种编码。

一些有用的链接: