Created
June 27, 2012 03:24
-
-
Save hidsh/2579ce130e6fff7b260c to your computer and use it in GitHub Desktop.
python: Removes HTML or XML character references and entities from a text string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# unescape_html_ent.py | |
# | |
# thx: | |
# 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("&#?\w+;", fixup, text) | |
###### test | |
if __name__ == '__main__': | |
print unescape(r"MXAM Internal Error (For support please contact [email protected]): MXAM Exception 015: Model cannot be set into required compile mode. : Error calling mes_setmode: unable to set system 'sctfs' into compile mode. エラー ==> mes_setmode at 272 複数の原因によるエラー。.") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment