0

我已经根据这个答案对脚本进行了一些修改。我遇到了 unicode 问题。有些问题最终写得不好。

一些答案和响应最终看起来像:

Yeah.. I know.. I’m a simpleton.. So what’s a Singleton? (2)

我怎样才能使’被翻译成正确的字符?

注意:如果这很重要,我在法式窗口上使用 python 2.6。

>>> sys.getdefaultencoding()
'ascii'
>>> sys.getfilesystemencoding()
'mbcs'

EDIT1:根据 Ryan Ginstrom 的帖子,我已经能够更正部分输出,但我遇到了 python 的 unicode 问题。

在空闲/python shell 中:

是的.. 我知道.. 我是个傻子.. 那么单身人士呢?

在文本文件中,重定向标准输出时

是的..我知道..我是个傻瓜..那么什么是单例?

我该如何纠正?


Edit2:我已经尝试过 Jarret Hardie 的解决方案,但它没有做任何事情。我在 Windows 上,使用 python 2.6,所以我的站点包文件夹位于:

C:\Python26\Lib\site-packages

没有 siteconfig.py 文件,所以我创建了一个,粘贴了 Jarret Hardie 提供的代码,启动了一个 python 解释器,但似乎还没有加载。

sys.getdefaultencoding() 'ascii'

我注意到在以下位置有一个 site.py 文件:

C:\Python26\Lib\site.py

我尝试更改函数中的编码

def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

将编码设置为 utf-8。它起作用了(当然是在重新启动python之后)。

>>> sys.getdefaultencoding()
'utf-8'

可悲的是,它没有纠正我程序中的字符。:(

4

2 回答 2

1

您应该能够将 HTMl/XML 实体转换为 Unicode 字符。在 SO 中查看这个答案:

使用 Python 解码 HTML 实体

基本上你想要这样的东西:

from BeautifulSoup import BeautifulStoneSoup

soup = BeautifulStoneSoup(urllib2.urlopen(URL),
                          convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
于 2009-04-08T06:58:41.353 回答
0

更改 siteconfig.py 中的默认编码是否有效?

在您的站点包文件(在我的 OS X 系统上/Library/Python/2.5/site-packages/)中,创建一个名为siteconfig.py. 在这个文件中放:

import sys
sys.setdefaultencoding('utf-8')

一旦 siteconfig.py 被处理,setdefaultencoding 方法就会从 sys 模块中删除,因此您必须将它放在 site-packages 中,以便 Python 在解释器启动时读取它。

于 2009-04-09T00:28:01.627 回答