gpt4 book ai didi

python - 为什么即使使用编码也无法在 python 中显示汉字?

转载 作者:太空狗 更新时间:2023-10-30 02:32:13 25 4
gpt4 key购买 nike

我只是想导入一个中文txt文件并打印出内容。这是我从网上复制的txt文件的内容,简体中文:http://stock.hexun.com/2013-06-01/154742801.html

起初,我试过这个:

userinput = raw_input('Enter the name of a file')
f=open(userinput,'r')
print f.read()
f.close()

可以打开文件打印,但是显示的是乱码。然后我尝试了以下编码:

#coding=UTF-8
userinput = raw_input('Enter the name of a file')
import codecs
f= codecs.open(userinput,"r","UTF-8")
str1=f.read()
print str1
f.close()

但是,它向我显示一条错误消息。UnicodeEncodeError: 'cp950 codec can't encode character u'\u76d8' in position 50:illegal mutibyte sequence.

为什么会出现这个错误?如何解决?我已经尝试过其他 unicode,例如 Big5、cp950...但它仍然无法正常工作。

最佳答案

它是您用来显示字符的终端系统。在 Windows 7 上使用 IDLE,它工作正常:

>>> val = u'\u76d8'
>>> print val

但是如果我使用 cmd.exe 就会收到你的错误。

使用支持unicode编码的终端显示方式。

关于python - 为什么即使使用编码也无法在 python 中显示汉字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com