编解码器不能编码字符:字符映射到<undefined> </undefined>

时间:2014-07-25 02:25:30

标签: python

我尝试使用以下代码在python 2.7中读取docx文件:

import docx
document = docx.Document('sim_dir_administrativo.docx')
    docText = '\n\n'.join([
        paragraph.text.encode('utf-8') for paragraph in document.paragraphs])

然后我尝试使用此代码解码文件中的字符串,因为我有一些特殊字符(例如ã):

print docText.decode("utf-8")

但是,我收到了这个错误:

    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position
 494457: character maps to <undefined>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

打印功能只能打印本地编码的字符。您可以找到sys.stdout.encoding的内容。要使用特殊字符进行打印,您必须先编码为本地编码。

# -*- coding: utf-8 -*-
import sys

print sys.stdout.encoding
print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
print u"Стоескер".encode(sys.stdout.encoding, errors='replace')

此代码段取自this stackoverflow response

相关问题