头疼!请问在 CLI 中怎么设置语言变量打印出\u5929 这中用[Python u"\u5929"] 表示的汉字。求教一下。在网上搜的乱七八糟的。

2016-08-21 22:10:21 +08:00
 theodorus
LC_ALL="zh_CN.UTF-8"?
我用的是debian。弄得我好辛苦= =
2504 次点击
所在节点    Python
17 条回复
est
2016-08-21 22:15:04 +08:00
赞头像。。。
theodorus
2016-08-21 22:16:19 +08:00
@est 别别别。人是丢了, 学点东西回去就可以了 233
tomczhen
2016-08-21 22:19:50 +08:00
你为什么不先去问一下神奇海螺呢?

编码问题是基础啊,就算你问到了 python 解决方法的代码,不了解编码到底是怎么回事,还是会在其他地方遇到编码的坑的。这种大部分人都遇到过的坑,自己动手搜索一下都一大堆文章和资料。
billlee
2016-08-21 22:20:38 +08:00
试了下 print(u"\u5929"), 出来的就是中文啊
billlee
2016-08-21 22:21:42 +08:00
youKnowDai
2016-08-21 22:23:02 +08:00
echo $LANG
export LANG="zh_CN.UTF-8"?
theodorus
2016-08-21 22:25:45 +08:00
@tomczhen 我当然问啦。我上了谷歌, 鸟哥的站。我用了那个 dpkg-reconfigure locales 可是不行啊。我编码理解还好。主要是不知道怎么设置啊。
theodorus
2016-08-21 22:26:23 +08:00
@billlee 假如你的 LANG 和 LC_ALL 是 en_US.UTF-8 的话会报错。
theodorus
2016-08-21 22:27:53 +08:00
[root@Debian 4test]#export LANG=zh_CN.UTF-8
[root@Debian 4test]#./test.py
Traceback (most recent call last):
File "./test.py", line 3, in <module>
print u"\u5929"
UnicodeEncodeError: 'ascii' codec can't encode character u'\u5929' in position 0: ordinal not in range(128)
[root@Debian 4test]#


我还试了 LC_ALL 等。还有 dpkg-reconfigure locales 等命令。可是不行啊。。。感觉要安装中文字体库?
theodorus
2016-08-21 22:30:53 +08:00
@billlee 得得得。既然都这么说, 那我还是再试试吧。这玩意困扰我很久了。我用的是 minial 版的。
billlee
2016-08-21 22:33:10 +08:00
@theodorus 我复现不了。这个理论上和 en_US/zh_CN 是没有关系的,只要编码是 UTF-8, 终端字体支持中文,就可以显示
theodorus
2016-08-21 22:37:55 +08:00
@billlee 没错我终端是 ssh 连接。然后编码如下
[root@Debian 4test]#locale -a
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory
C
C.UTF-8
POSIX
en_US.utf8


我的终端是 mac 的 terminal 已经设置为支持中文的 GBK, UTF-8 等格式编码。能够显示中文。使用 ls 命令可以看到中文文件名称。也可输入。

但是 python 无法解析这个让我很头疼。
theodorus
2016-08-21 22:42:24 +08:00
@billlee 我应该发现问题了。麻烦你们了。应该是我必须设置 python 为 utf-8 编码。否则会自动设为 ascii 编码。我去多学习学习, 不随便发帖了。抱歉各位。
only0jac
2016-08-21 22:42:41 +08:00
@billlee 用 py 的话,如果字符串变量中包含 unicode 字符,该怎么转回来?谢谢
Sasasu
2016-08-21 22:44:47 +08:00
文件里 /etc/locale.gen 加
en_US.UTF-8 UTF-8
zh_CN.UTF-8 UTF-8
zh_TW.UTF-8 UTF-8

运行
locale-gen
theodorus
2016-08-21 22:48:56 +08:00
@Sasasu 我将 python 文件设置为 utf-8 编码之后并且也按照你说的做了。可是还是无法打印出汉字。不知为何。在 mac 自带的 terminal 里面可以打出汉字。通过 ssh 连接 debian 里面却不能。我不知为何, 请问你能否告诉我原因吗?
exoticknight
2016-08-21 22:51:37 +08:00
windows , utf-8 格式,亲测 cmd 里面都行, code page 936
#!/usr/bin/env python
# _*_ coding: utf-8 _*_

print(u"\u5929")

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/300826

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX