代码之家  ›  专栏  ›  技术社区  ›  Martin

如何将html实体转换为符号?

  •  0
  • Martin  · 技术社区  · 17 年前

    我已经做了一些调整 the script from this answer

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

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

    ’ 要翻译成正确的字符?

    注意:如果这很重要的话,我正在法国windows上使用Python2.6。

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

    根据Ryan Ginstrom的帖子,我已经能够纠正部分输出,但是python的unicode有问题。

    在Idle/python shell中:

    是 啊我知道。。我是个傻瓜。。所以 什么是单身?

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

    是 啊我知道。。我是个傻瓜。。所以 什么是单身?

    我该怎么纠正呢?


    编辑2: 我试过Jarret Hardie的解决方案,但没有任何效果。 我在windows上,使用python 2.6,因此我的站点包文件夹位于:

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

    sys.getdefaultencoding()

    我注意到在以下位置有一个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'
    

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

    2 回复  |  直到 9 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    您应该能够将HTMl/XML实体转换为Unicode字符。请在中查看此答案,以便:

    Decoding HTML Entities With Python

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

    from BeautifulSoup import BeautifulStoneSoup
    
    soup = BeautifulStoneSoup(urllib2.urlopen(URL),
                              convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
    
        2
  •  0
  •   Jarret Hardie    17 年前

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

    在您的站点软件包文件中(在我的OS X系统上) /Library/Python/2.5/site-packages/ siteconfig.py . 在该文件中,输入:

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

    一旦处理了siteconfig.py,setdefaultencoding方法就会从sys模块中删除,因此必须将其放入站点包中,以便Python在解释器启动时读取它。