我使用PDFminer的pdf2text将PDF缩减为文本.不幸的是它包含特殊字符.让我显示我的控制台的输出
>>>a=pdf_to_text("ap.pdf")
Run Code Online (Sandbox Code Playgroud)
下面是一个样本,有点截断
>>>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'
Run Code Online (Sandbox Code Playgroud)
我明白我必须编码
>>>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)
Run Code Online (Sandbox Code Playgroud)
我搜索了一下并尝试了它们,特别是在python中替换特殊字符.输入来自PDFminer,所以它很难控制(AFAIK).从这个输出中制作正确明文的方法是什么?
我究竟做错了什么?
- 快速修复:将PDFminer的编解码器更改为ascii-但这不是一个持久的解决方案 -
- 为解决方案安排快速修复 - 更改编解码器删除信息 -
- Maxim提到的一个相关话题http://en.wikipedia.org/wiki/Windows-1251 -
Max*_*kin 11
当非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
Run Code Online (Sandbox Code Playgroud)
基本上,上面的代码片段执行iconv --from-code=CP1251 --to-code=UTF-8命令操作,即它将字符串从一个编码转换为另一个编码.
一些有用的链接:
| 归档时间: |
|
| 查看次数: |
5527 次 |
| 最近记录: |