Python将文件内容转换为Unicode格式 [英] Python convert file content to unicode form

查看:526
本文介绍了Python将文件内容转换为Unicode格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个文件a.js,其内容为:

For example, I have a file a.js whose content is:

Hello, 你好, bye.  

其中两个汉字的unicode格式为 \u4f60\u597d

我想编写一个python程序,将a.js中的汉字转换为unicode形式以输出b.js,其内容应为:你好,\u4f60\u597d,再见

Which contains two Chinese characters whose unicode form is \u4f60\u597d
I want to write a python program which convert the Chinese characters in a.js to its unicode form to output b.js, whose content should be: Hello, \u4f60\u597d, bye.

我的代码:

fp = open("a.js")
content = fp.read()
fp.close()

fp2 = open("b.js", "w")
result = content.decode("utf-8")
fp2.write(result)
fp2.close()  

,但似乎汉字仍然是一个字符,而不是我想要的ASCII字符串。

but it seems that the Chinese characters are still one character , not an ASCII string like I want.

推荐答案

>>> print u'Hello, 你好, bye.'.encode('unicode-escape')
Hello, \u4f60\u597d, bye.

但是您应该考虑通过 json

But you should consider using JSON, via json.

这篇关于Python将文件内容转换为Unicode格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆