2.17在字符串中处理html和xml
问题
你想将HTML或者XML实体如&entity;或&#code;替换为对应的文本。再者,你需要转换文本特定的字符(比如<,>或者&)。
解决方案
如果你想替换文本字符串中的'<'或者'>',使用html.escape()函数可以很容易的完成。比如:
s='The report said the human rights situation in the"<tag> text</tag>"'
import html
print(s) # ->The report said the human rights situation in the"<tag> text</tag>"
print(html.escape(s)) # ->
The report said the human rights situation in the"<tag> text</tag>"
print(html.escape(s,quote=False)) # ->The report said the human rights situation in the"<tag> text</tag>"
如果你真正处理的是ASCII文本,并且想将非ASCII文本对应的编码实体嵌入进去,可以给某些I/O函数传递参数errors=’xmlcharrefreplace'来达到这个目的。比如。
s='Spicy Jalapeño'
print(s.encode('ascii',errors='xmlcharrefreplace')) # ->b'Spicy Jalapeño'
为了替换文本中的编译实体,你需要使用另一种方法。如果你正在处理HTML或者xml文本,试着先使用一个合适的HTML或者xml解析器。通常情况下,这些工具会自动替换这些编码值,你无需担心。
有时候,如果你接受到了一些含有编码值的原始文本,需要手动去做替换,通常你只需要使用HTML或者XML解析器的一些相关工具函数/方法即可。比如:
s='Spicy &qout ;Jalapeño&qout.'
from html import unescape
print(unescape(s)) # ->Spicy &qout ;Jalapeño&qout.
t='The prompt is >>>'
from xml.sax.saxutils import unescape
print(unescape(t)) # ->The prompt is >>>
讨论
在生成HTML或者XML文本的时候,如果正确的转换特殊标记字符是一个很容易被忽略的细节。特别当你使用print()函数或者其他字符串串格式来产生输出的时候。使用像html.escape()的工具函数可以很容易的解决这类问题。

浙公网安备 33010602011771号