简体   繁体   English

在python控制台中显示汉字

[英]Display chinese characters in python console

I know related questions have been asked but my case is a bit specific because I run my code in a Docker container, and I haven't been able to make other solutions work.我知道有人问过相关问题,但我的情况有点具体,因为我在 Docker 容器中运行我的代码,但我无法使其他解决方案起作用。

I'm using python 2.7 to translate an english text to chinese (and other non-latin languages), using the translate module:我正在使用 python 2.7 将英文文本翻译成中文(和其他非拉丁语言),使用 translate 模块:

from translate import Translator
text = 'Hello'
translator= Translator(to_lang='zh')
translated_text=translator.translate(text)
print(translated_text.encode('utf-8'))

This last command fails to display the chinese text in the console, it just displays question marks.最后一条命令无法在控制台中显示中文文本,它只显示问号。 From the doc, translate() is supposed to output a unicode string.从文档中, translate() 应该输出一个 unicode 字符串。

I'm running this in an Ubuntu 16.04 Docker container and Windows as host.我在 Ubuntu 16.04 Docker 容器和 Windows 作为主机中运行它。 So maybe the problem comes with Ubuntu or Windows not having the right configuration to display these characters but I don't know how to check that.因此,问题可能在于 Ubuntu 或 Windows 没有正确的配置来显示这些字符,但我不知道如何检查。 Any help will be much appreciated.任何帮助都感激不尽。

I was able to display Chinese characters on windows console using:我能够使用以下命令在 Windows 控制台上显示中文字符:

from translate import Translator
text = 'Hello'
translator= Translator(to_lang='zh')
translated_text=translator.translate(text)
print(translated_text) # read notes
# 您好

Notes:笔记:
Before running the script , make sure you set the correct Default code page of windows console to “936 (ANSI/OEM – Simplified Chinese GBK)” .在运行脚本之前,请确保将正确的 Windows 控制台Default code page设置为“936 (ANSI/OEM – Simplified Chinese GBK)” You can do this by typing chcp 936 on the console, ie:您可以通过在控制台上键入chcp 936来执行此操作,即:

chcp 936
python myscript.py
您好

Source: https://www.walkernews.net/2013/05/19/how-to-get-windows-command-prompt-displays-chinese-characters/来源: https : //www.walkernews.net/2013/05/19/how-to-get-windows-command-prompt-displays-chinese-characters/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM