如何在Python 3.1中取消转义字符串中的HTML实体?

2024-05-11 21:07:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我环顾了四周,只找到了Python2.6和更早版本的解决方案,但在Python3.X中没有关于如何做到这一点的任何内容(我只能访问Win7 box)

我必须能够在3.1中做到这一点,最好没有外部库。目前,我已经安装了httplib2并可以访问命令提示符curl(这就是我获取页面源代码的方式)。不幸的是,curl没有解码html实体,据我所知,我在文档中找不到解码它的命令。

是的,我试过让漂亮的汤工作,很多次在3.X中都没有成功。如果你能提供如何在微软Windows环境下让它在python 3中工作的明确说明,我将非常感激。

所以,为了清楚起见,我需要把这样的字符串:Suzy & John变成这样的字符串:“Suzy&John”。


Tags: 字符串版本box内容源代码页面curl解决方案
3条回答

您可以使用函数html.unescape

Python3.4+中(感谢J.F.Sebastian的更新):

import html
html.unescape('Suzy & John')
# 'Suzy & John'

html.unescape('"')
# '"'

Python3.3或更早的时候:

import html.parser    
html.parser.HTMLParser().unescape('Suzy & John')

在Python2中:

import HTMLParser
HTMLParser.HTMLParser().unescape('Suzy & John')

您可以为此目的使用^{}。该模块包含在Python标准库中,可在Python 2.x和Python 3.x之间移植

>>> import xml.sax.saxutils as saxutils
>>> saxutils.unescape("Suzy & John")
'Suzy & John'

显然,我没有足够高的声誉做任何事,除了张贴这个。联合国大学的答复并没有改变引文。我唯一发现的就是这个功能:

import re
from htmlentitydefs import name2codepoint as n2cp

def decodeHtmlentities(string):
    def substitute_entity(match):        
        ent = match.group(2)
        if match.group(1) == "#":
            return unichr(int(ent))
        else:
            cp = n2cp.get(ent)
            if cp:
                return unichr(cp)
            else:
                return match.group()
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
    return entity_re.subn(substitute_entity, string)[0]

我从这里得到的。

相关问题 更多 >