如何在Python中使用其他语言与其他字符?

时间:2016-02-23 18:07:21

标签: python unicode python-2.x

我试图通过以下程序传递Python中其他语言的字母:

theWord = "阿麗思道"
theWord = theWord.decode('unicode-escape')
print theWord

我一直收到以下错误:

  

UnicodeEncodeError:&#39; charmap&#39;编解码器不能对字符u&#39; \ x98&#39;进行编码。在位置1:字符映射到<undefined>

设置正确的unicode是件事,但我找不到任何东西。有人知道吗?

我需要让角色完全通过,因为我试图通过中文翻译程序传递它们,所以我试图让翻译出来。

3 个答案:

答案 0 :(得分:1)

这样的事情? (取自how to print chinese word in my code.. using pythonPython - 'ascii' codec can't decode byte

# coding = utf-8
theWord = "阿麗思道"
theWord = theWord.decode('utf-8').encode('utf-8')
print theWord

答案 1 :(得分:1)

我认为问题出在你正在使用的解码中,请查看

# -*- coding: utf-8 -*-

chinase = "阿麗思道"
print "original:", chinase
print "repr:", repr(chinase)
print
x = chinase.decode('unicode-escape')
print 'unicode-escape:', x
print "repr:",repr(x)
print
y = chinase.decode('utf-8')
print 'utf-8', y
print "repr",repr(y)

当我跑它时,我得到了

original: 阿麗思道
repr: '\xe9\x98\xbf\xe9\xba\x97\xe6\x80\x9d\xe9\x81\x93'

unicode-escape: é¿éºæé
repr: u'\xe9\x98\xbf\xe9\xba\x97\xe6\x80\x9d\xe9\x81\x93'

utf-8 阿麗思道
repr u'\u963f\u9e97\u601d\u9053'

所以只需使用decode('utf-8')就可以了。

修改

有趣的是,如果我在Windows中的cmd中运行它,我会得到输出和你做的相同的错误,我得出的结论是问题就在你要运行它的地方,因为cmd只支持ascii您尝试在其中显示的任何其他字符都是不可能的,因为它会尝试将其转换为该设备的编码但在此过程中失败,因此您必须更改为具有适当支持unicode的编辑器,例如与python一起出现的IDLE或没有任何打印的工作

答案 2 :(得分:0)

检查您的控制台编码,该编码可能不是UTF-8,这可能是字符无法在控制台上打印的原因。 如果将输出写入UTF-8编码的文件中,那么它将起作用。

theWord = "阿麗思道"
fp=open("out.txt","wb")
theWord = fp.write(bytes(theWord.encode('utf-8')))
fp.close()