Sulli
Sulli

Reputation: 829

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.

I'm using python 2.7 to translate an english text to chinese (and other non-latin languages), using the translate module:

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.

I'm running this in an Ubuntu 16.04 Docker container and Windows as host. 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. Any help will be much appreciated.

Upvotes: 3

Views: 2380

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98861

I was able to display Chinese characters on windows console using:

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)”. You can do this by typing chcp 936 on the console, i.e.:

chcp 936
python myscript.py
您好

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

Upvotes: 2

Related Questions