我遇到了这段python代码(粘贴在下面)effbot http://effbot.org/zone/re-sub.htm#unescape-html我想知道:
为什么要在函数中定义函数?
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)
为什么要在函数中定义函数?
使其保持隔离。只用在这一个地方。当它在本地使用时,为什么要更全局地定义它?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)