Using Chinese to build a dictionary in Python

我是研究僧i 提交于 2021-02-04 13:53:29

问题


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...


回答1:


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 --> 你好



回答2:


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

>>> d = {"Hello" : "你好"}
>>> print d["Hello"]
你好


来源:https://stackoverflow.com/questions/6988213/using-chinese-to-build-a-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!