如何在 Python 3.1 中取消转义字符串中的 HTML 实体?[重复]
- 2025-02-25 09:09:00
- admin 原创
- 36
问题描述:
我四处寻找,只找到了针对 Python 2.6 及更早版本的解决方案,没有找到有关如何在 Python 3.X 中执行此操作的任何信息。(我只能访问 Win7 框。)
我必须能够在 3.1 中做到这一点,最好不使用外部库。目前,我已经安装了 httplib2 并可以访问命令提示符 curl(这就是我获取页面源代码的方式)。不幸的是,curl 不会解码 html 实体,据我所知,我在文档中找不到解码它的命令。
是的,我尝试过让 Beautiful Soup 在 3.X 中运行很多次,但都没有成功。如果您能提供关于如何在 MS Windows 环境中使用 Python 3 运行它的明确说明,我将不胜感激。
因此,为了清楚起见,我需要将这样的字符串转换Suzy & John
为这样的字符串:“Suzy & John”。
解决方案 1:
您可以使用函数html.unescape:
在Python3.4+中(感谢 JF 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')
解决方案 2:
您可以将其用于xml.sax.saxutils.unescape
此目的。此模块包含在 Python 标准库中,可在 Python 2.x 和 Python 3.x 之间移植。
>>> import xml.sax.saxutils as saxutils
>>> saxutils.unescape("Suzy & John")
'Suzy & John'
解决方案 3:
显然,我的声誉不够高,除了发布此帖外什么也做不了。unutbu 的答案没有取消转义引号。我发现唯一能做到这一点的是这个函数:
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]
这是我从这个页面得到的。
解决方案 4:
Python 3.x也有html.entities
解决方案 5:
在我的例子中,我有一个在 as3 转义函数中转义的 html 字符串。经过一个小时的谷歌搜索,没有找到任何有用的东西,所以我编写了这个递归函数来满足我的需求。它在这里,
def unescape(string):
index = string.find("%")
if index == -1:
return string
else:
#if it is escaped unicode character do different decoding
if string[index+1:index+2] == 'u':
replace_with = ("\\\"+string[index+1:index+6]).decode('unicode_escape')
string = string.replace(string[index:index+6],replace_with)
else:
replace_with = string[index+1:index+3].decode('hex')
string = string.replace(string[index:index+3],replace_with)
return unescape(string)
编辑-1添加了处理unicode字符的功能。
解决方案 6:
我不确定这是否是一个内置库,但它看起来像你需要的并且支持 3.1。
来自:http://docs.python.org/3.1/library/xml.sax.utils.html ?highlight=html%20unescape
xml.sax.saxutils.unescape(data, entities={}) 对数据字符串中的 '&'、'<' 和 '>' 进行取消转义。
- 2024年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)