Python中的其他字符如何使用另一种语言?

How to use another language with other characters in Python?

我正在尝试通过这样的程序传递 Python 中另一种语言的字母:

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

我不断收到以下错误:

UnicodeEncodeError: 'charmap' codec can't encode character u'\x98' in position 1: character maps to <undefined>

这与设置正确的 unicode 有关,但我在上面找不到任何内容。有人知道吗?

我需要让字符通过,因为我正试图通过一个中文翻译程序来传递它们,所以我想把翻译出来。

像这样的? (摘自 how to print chinese word in my code.. using python, Python - 'ascii' codec can't decode byte

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

我认为问题出在您使用的解码器上,检查一下

# -*- 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,或者在没有任何打印的情况下工作

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

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