在Python中使用中文构建字典

发布于 2024-11-28 07:14:54 字数 528 浏览 1 评论 0 原文

这是我第一次来这里,而且我对 Python 世界还是个新手。我也在学习中文,我想创建一个程序来使用字典复习中文词汇。这是我通常使用的代码:

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

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

print(dictionary)

我不断得到的结果是这样的:

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

我还尝试在带有汉字的字符串的开头添加一个“u”,甚至方法“.encode('utf-8” '),但我通常在 Geany IDE 上工作,我尝试检查所有首选项,并且我已阅读 PEP 网页 以及发布的许多其他问题很有趣,它适用于字符串和 raw_input 方法,但没有其他...

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌能量女王 2024-12-05 07:14:54

打印字典时(例如print(dictionary)),会显示键和值的repr

相反,尝试:

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

产量:

Hello --> 你好

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 --> 你好
神经大条 2024-12-05 07:14:54

如果直接打印值,您可以看到字符:

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

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

>>> d = {"Hello" : "你好"}
>>> print d["Hello"]
你好
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文