如何在Python3中更改字节对象的编码?

如何在Python3中更改字节对象的编码?,python,json,python-3.x,encoding,character-encoding,Python,Json,Python 3.x,Encoding,Character Encoding,我写了一个程序来抓取网页以获得json字幕。json是波斯语。我使用解码(“utf-8”),但我的角色是代码。 我该怎么办 我的python是3.4,我的操作系统是windows8,这是我的代码: >>> import urllib.request as urllib2 >>> print(urllib2.urlopen('http://www.ted.com/talks/subtitles/id/667/lang/fa').read().decode("ut

我写了一个程序来抓取网页以获得json字幕。json是波斯语。我使用解码(“utf-8”),但我的角色是代码。 我该怎么办

我的python是3.4,我的操作系统是windows8,这是我的代码:

>>> import urllib.request as urllib2
>>> print(urllib2.urlopen('http://www.ted.com/talks/subtitles/id/667/lang/fa').read().decode("utf-8"))

{"captions":[{"duration":4000,"content":"\u0627\u0645\u0631\u0648\u0632\u0647 \u062a\u0645\u0627\u0645 \u0628\u0646\u0627\u0647\u0627 \u06cc\u06a9 \u0686\u06cc\u0632 \u0645\u0634\u062a\u0631\u06a9 \u062f\u0627\u0631\u0646\u062f.","startOfParagraph"...
第一行是:

我使用这种方式将字符串写入文件,但问题仍然存在:

with open('D:\\result.json', 'w') as fid:
    fid.write(urllib2.urlopen('http://www.ted.com/talks/subtitles/id/667/lang/fa').read().decode("utf-8"))

这里有JSON,阿拉伯字符转义为。为了撤消转义,您需要用解析它。完成后,您应该能够提取“contents”值并将其打印(到一个文件中,因为控制台上有Windows)。大概是这样的:

>>> import urllib.request as urllib2
>>> result = json.loads(urllib2.urlopen('...').read().decode('utf8'))
>>> with open('example.txt', 'w', encoding='utf8') as f:
...     print(result['captions'][0]['content'], file=f)

然后,您应该能够使用所选的编辑器打开example.txt。如果显示不正确,请确保将编码设置为UTF-8。

这里有JSON,阿拉伯字符转义为。为了撤消转义,您需要用解析它。完成后,您应该能够提取“contents”值并将其打印(到一个文件中,因为控制台上有Windows)。大概是这样的:

>>> import urllib.request as urllib2
>>> result = json.loads(urllib2.urlopen('...').read().decode('utf8'))
>>> with open('example.txt', 'w', encoding='utf8') as f:
...     print(result['captions'][0]['content'], file=f)
然后,您应该能够使用所选的编辑器打开example.txt。如果显示不正确,请确保将编码设置为UTF-8