python - 如何在Python中输出汉字?

标签 python unicode jupyter-notebook

我的数据集中的['douban_info']列是有关存储在JSON中的中文电影的信息,所以当我执行df['douban_info'][0],它返回:

enter image description here

汉字都变成了\u7834\u6653\u8005之类的东西,看不懂。有没有可能让Python在输出的时候把它们变成原来的中文?

我在 Jupyter Notebook 中使用 Python 2.7。

最佳答案

这就是 Python 2 的工作原理。默认情况下,它在生成列表和字符串的显示字符串时显示 repr()。您必须打印字符串才能查看 Unicode 字符:

>>> D = {u'aka': [u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)', u'\u9ece\u660e\u65f6\u5206']}
>>> D[u'aka'][0]
u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)'
>>> print D[u'aka'][0]
2019猎血都市(港)

如果您无法迁移到 Python 3,并且不喜欢默认的 repr() 显示,则必须创建自己的显示例程。像这样的东西:

D = {u'aka':[u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)',u'\u9ece\u660e\u65f6\u5206']}

def dump(item):
    L = []
    if isinstance(item,dict):
        for k,v in item.items():
            L.append(dump(k) + ':')
            L.append(dump(v))
        return '{' + ', '.join(L) + '}'
    elif isinstance(item,list):
        for i in item:
            L.append(dump(i))
        return '[' + ', '.join(L) + ']'
    else:
        return "u'" + item + "'"

print dump(D)

输出:

{u'aka':, [u'2019猎血都市(港)', u'黎明时分']}

请注意,作为通用转储实用程序,这绝不是完整的。

在 Python 3 中 repr() 已更新:

>>> print(D)
{'aka': ['2019猎血都市(港)', '黎明时分']}

关于python - 如何在Python中输出汉字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39805113/

相关文章:

python - Django:如何在 Django 过滤方法中使用 "or"?

C++ & boost : encode/decode UTF-8

Python:用 unidecode 解决 unicode hell

python - matplotlib scatter 在 ipython 笔记本中有效,但在控制台中无效

python - 弹出/扩展 jupyter 单元格到新的浏览器窗口

python - 如何使用 Anaconda (Python 3) 中的 Spyder 解决此编码问题?

python - 在opencv中绘制轮廓

python - Google Collab 如何显示作业的值(value)?

python - 计算 Python 字符串中的字符频率

java - java中的UTF编码