Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Chinese to build a dictionary in Python

so this is my first time here, and also I am new to the world of Python. I am studying Chinese also and I wanted to create a program to review Chinese vocabulary using a dictionary. Here is the code that I normally use:

#!/usr/bin/python
# -*- coding:utf-8-*-

dictionary = {"Hello" : "你好"} # Simple example to save time

print(dictionary)

The results I keep getting are something like:

{'hello': '\xe4\xbd\xa0\xe5\xa5\xbd'}

I have also trying adding a "u" to the beginning of the string with the Chinese characters, and even the method ".encode('utf-8'), yet no of these seem to work. I normally work off of the Geany IDE. I have tried to check out all of the preferences, and I have read the PEP web page along with many of the other questions posted. It is funny, it works with strings and the raw_input method, but nothing else...

like image 480
Jeremy Wittkopp Avatar asked Aug 08 '11 20:08

Jeremy Wittkopp


2 Answers

When printing a dict, (e.g. print(dictionary)), the reprs of the keys and values are displayed.

Instead, try:

dictionary = {u"Hello" : u"你好"} 
for key,value in dictionary.iteritems():
    print(u'{k} --> {v}'.format(k=key,v=value))

yields:

Hello --> 你好
like image 75
unutbu Avatar answered Sep 22 '22 01:09

unutbu


You can see the characters if you print the values directly:

>>> d = {"Hello" : "你好"}
>>> print d["Hello"]
你好
like image 29
EinLama Avatar answered Sep 23 '22 01:09

EinLama