我需要解析各种文本源,然后将其打印/存储在某处。
每次遇到非 ASCII 字符时,我都无法正确打印它,因为它被转换为字节,而且我不知道如何查看正确的字符。
(我是 Python 的新手,我来自 PHP,我从来没有遇到过任何 utf-8 问题)
下面是一个代码示例:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import codecs
import feedparser
url = "http://feeds.bbci.co.uk/japanese/rss.xml"
feeds = feedparser.parse(url)
title = feeds['feed'].get('title').encode('utf-8')
print(title)
file = codecs.open("test.txt", "w", "utf-8")
file.write(str(title))
file.close()
我想打印并在文件中写入 RSS 标题(BBC 日语 - ホーム),但结果是这样的:
b’BBC 日语 - \xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0’
在屏幕和文件上。有没有正确的方法来做到这一点?
原文由 Omiod 发布,翻译遵循 CC BY-SA 4.0 许可协议
In python3
bytes
andstr
are two different types - andstr
is used to represent any type of string (also unicode), when youencode()
一些东西,你将它从它的str
表示转换为它的bytes
表示特定编码。在您的情况下,为了解码字符串,您只需要删除
encode('utf-8')
部分: