【问题标题】:how to get rid of unicode characters in python output?如何摆脱python输出中的unicode字符?
【发布时间】:2016-08-21 17:09:35
【问题描述】:

我正在尝试加载一个 json 文件,然后尝试稍后对其进行解析。 但是,在输出中我不断得到“u”字符。 我尝试使用 encoding='utf-8' 打开文件,这可以解决问题。 我正在使用python 2.7。是否有一种直接的方法或解决方法可以忽略输出中的“u”字符。

import json
import io


with io.open('/tmp/install-report.json', encoding='utf-8') as json_data:
    d = json.load(json_data)
    print d

o/p

{u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544,}}

ps:我通过这篇文章Suppress the u'prefix indicating unicode' in python strings 但这没有适用于 python 2.7 的解决方案

【问题讨论】:

  • 简而言之:no.
  • 为什么会出现问题?
  • Unicode 与问题无关。这是一个充满字符串的字典的 Python (repr()) 表示。如果您想要其他格式的表示,例如 JSON,请使用该格式的编码器。
  • @PadraicCunningham 这是一个问题,因为这需要显示给可能对这些“字符”不满意的最终用户
  • @cool77 但是您已经假设最终用户对 python repr 输出感到满意?首先,你期望什么样的输出?时间戳看起来对最终用户也不友好。

标签: python json unicode


【解决方案1】:

使用 json.dumps 并对其进行解码以将其转换为字符串

data = json.dumps(d, ensure_ascii=False).decode('utf8')
print data

【讨论】:

  • @cool77 如果解决了您的问题,请将答案标记为正确
  • 我尝试了解决方案。它有助于。但我需要稍后在脚本中使用来自 json.load 的字典“d”。通过使用 json.dumps ,我得到了一个字符串,以后我不能像在字典中那样迭代它/
  • 所以保留d 字典和data 字符串并使用您需要的任何一个。
【解决方案2】:

u 只是表示一个 Unicode 字符串。如果打印字符串,则不会显示:

d = {u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544}}

print 'Status:',d[u'install'][u'Status']

输出:

Status: In Progress...

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多