打印utf-8编码的字符串

dan*_*iel 27 python unicode encoding

我正在使用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__
Run Code Online (Sandbox Code Playgroud)

当我尝试打印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 '
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ers 24

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

s = unicode(your_object).encode('utf8')
f.write(s)
Run Code Online (Sandbox Code Playgroud)

  • 你的进口报表是什么? (5认同)

Nir*_*evy 11

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

比照.在Python中通过sys.stdout编写unicode字符串.

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