【问题标题】:Python unicode file reencodingPython unicode 文件重新编码
【发布时间】:2016-04-24 20:47:26
【问题描述】:

关于 SO 中的 Unicode 解码有很多问题,而这一套都不符合我的需求。

说,我需要处理一些json数据,这部分看起来像这样:

  u'message': {
    u'body': u'\u0441\u043f\u0430\u0441\u0438\u0431\u043e \u0431\u043e\u043b\u044c\u0448\u043e\u0435',
    u'user_id': 374298,
    u'title': u' ... ',
    u'date': 1461496370,
    u'read_state': 0,
    u'id': 4325364,
    u'out': 1
  }

唯一的目标是摆脱 unicode 以在“body”行中获取人类可读的文本:

  'message': {
    'body': 'cпасибо большое',
    'user_id': 374298,
    'title': ' ... ',
    'date': 1461496370,
    'read_state': 0,
    'id': 4325364,
    'out': 1
  }

只要有大量的json数据,我就修改了一些找到的python源代码如下:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

filePath = "/home/user/foo.txt"

outPath = filePath + ".new"

outText = ""

inF = open(filePath, "rb")
fContent = unicode(inF.read(), 'utf-8')
inF.close()

for everysymbol in fContent:
    if isinstance(everysymbol, unicode):
        outText += everysymbol.decode('cp1251')
    else: 
        pass

fContent = outText


outF = open(outPath, "wb")
outF.write(outText.decode("utf-8"))
outF.close()

不幸的是,此代码不会更改目标文件中的任何内容。如何真正将我的数据解码为人类可读的?

【问题讨论】:

  • 把 rb 和 wb 改成 r 和 w

标签: python json unicode


【解决方案1】:

你的数据不是json,而是已经解析的json数据。 Python 2 使用 repr() 打印字典和列表,它将非 ASCII 字符显示为转义码。直接打印字符串查看其内容,使用str():

import json

# Your already parsed data
data = {u'message': {
     u'body': u'\u0441\u043f\u0430\u0441\u0438\u0431\u043e \u0431\u043e\u043b\u044c\u0448\u043e\u0435',
     u'user_id': 374298,
     u'title': u' ... ',
     u'date': 1461496370,
     u'read_state': 0,
     u'id': 4325364,
     u'out': 1}}

# Write it to a file to generate real json-encoded data:
with open('foo.json','w') as f:
    json.dump(data,f,indent=2)

# Display actual json-encoded file:
with open('foo.json') as f:
    print f.read()
print

# reparse the data
with open('foo.json') as f:
    data = json.load(f)

# Printing dictionaries and lists escapes non-ASCII
print data
print

# But print the string directly and it is fine (assuming your terminal and font supports the characters):

print data[u'message'][u'body']

输出:

{
  "message": {
    "body": "\u0441\u043f\u0430\u0441\u0438\u0431\u043e \u0431\u043e\u043b\u044c\u0448\u043e\u0435", 
    "user_id": 374298, 
    "title": " ... ", 
    "date": 1461496370, 
    "read_state": 0, 
    "id": 4325364, 
    "out": 1
  }
}

{u'message': {u'body': u'\u0441\u043f\u0430\u0441\u0438\u0431\u043e \u0431\u043e\u043b\u044c\u0448\u043e\u0435', u'user_id': 374298, u'title': u' ... ', u'date': 1461496370, u'read_state': 0, u'id': 4325364, u'out': 1}}

спасибо большое

请注意,Python 3 不再为repr() 转义可打印的非ASCII。

【讨论】:

    【解决方案2】:
    #!/usr/bin/env python3
    import json
    
    filePath = "/home/user/foo.txt"
    
    outPath = filePath + ".new"
    
    with open(filePath, "rb") as f:
        fContent = json.loads(f.read())
    
    with open(outPath, "wb") as f:
        f.write(json.dumps(fContent, ensure_ascii=False).encode())
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-09-03
    • 2019-12-19
    • 2012-04-10
    • 2013-05-11
    • 1970-01-01
    • 2013-12-10
    • 2021-06-06
    • 2020-01-12
    相关资源
    最近更新 更多