【问题标题】:Printing a utf-8 encoded string打印一个 utf-8 编码的字符串
【发布时间】:2011-07-09 08:30:43
【问题描述】:

我正在使用 BeautifulSoup 从 HTML 中提取一些文本,但我不知道如何将其正确打印到屏幕(或相关的文件)。

这是包含文本的类的样子:

class Thread(object):
    def __init__(self, title, author, date, content = u""):
        self.title = title
        self.author = author
        self.date = date
        self.content = content
        self.replies = []

    def __unicode__(self):
        s = u""

        for k, v in self.__dict__.items():
            s += u"%s = %s " % (k, v)

        return s

    def __repr__(self):
        return repr(unicode(self))

    __str__ = __repr__

当尝试打印Thread 的实例时,我在控制台上看到了以下内容:

~/python-tests $ python test.py
u'date = 21:01 03/02/11 content =  author = \u05d3"\u05e8 \u05d9\u05d5\u05e0\u05d9 \u05e1\u05d8\u05d0\u05e0\u05e6\'\u05e1\u05e7\u05d5 replies = [] title = \u05de\u05d1\u05e0\u05d4 \u05d4\u05de\u05d1\u05d7\u05df '

无论我尝试什么,我都无法得到我想要的输出(上面的文本应该是希伯来语)。我的最终目标是将Thread 序列化为文件(使用 json 或 pickle)并能够将其读回。

我在 Ubuntu 10.10 上使用 Python 2.6.6 运行它。

【问题讨论】:

  • 前几天我在尝试使用 csv 模块写入 CSV 文档时遇到了类似的问题。皮塔饼。但是encode() 是要走的路。
  • 我也遇到了同样的问题,但这完全是因为我的 mysql 连接上没有 'charset=utf8' !

标签: python unicode encoding


【解决方案1】:

要将 Unicode 字符串输出到文件(或控制台),您需要选择 文本编码。在 Python 中,默认文本编码是 ASCII,但要支持希伯来字符,您需要使用不同的编码,例如 UTF-8:

s = unicode(your_object).encode('utf8')
f.write(s)

【讨论】:

  • 在内部 print x 调用 x.__str__ 并且在您的班级中您已将 __str__ 定义为与 __repr__ 相同。
  • __str__ 应该怎么做?如果我正确阅读文档,它不应该返回 unicode 对象。
  • 你的导入语句是什么?
【解决方案2】:

@mark 答案的一个不错的替代方法是设置环境变量PYTHONIOENCODING=UTF-8

c.fWriting unicode strings via sys.stdout in Python.

(确保在启动 Python 之前设置它,而不是在脚本中。)

【讨论】:

  • 是的!但是程序中的 os.putenv('PYTHONIOENCODING', 'UTF-8') 对我不起作用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多