PageRenderTime 24ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/test/util/build_page/libs/pywebsite/escape.py

https://bitbucket.org/pygame/pygame/
Python | 43 lines | 22 code | 15 blank | 6 comment | 6 complexity | 38918338bf7456e5efe35477970d834e MD5 | raw file
Possible License(s): LGPL-2.1
  1. # coding: utf-8
  2. ################################################################################
  3. import re
  4. import htmlentitydefs
  5. _escape_re = re.compile(eval(r'u"[&<>\"]|[\u0080-\uffff]+"'))
  6. ################################################################################
  7. def _escape_sub(match):
  8. try:
  9. entity_code = ord(match.group(0))
  10. except Exception, e:
  11. print match.group(0)
  12. raise
  13. named_entitiy = htmlentitydefs.codepoint2name.get(entity_code)
  14. if named_entitiy: return '&%s;' % named_entitiy
  15. else: return '&#%d;' % entity_code
  16. ################################################################################
  17. def escape(uni, codec=None):
  18. if codec: uni = uni.decode(codec)
  19. return _escape_re.sub(_escape_sub, uni)
  20. ehtml = escape
  21. __all__ = ['escape', 'ehtml']
  22. ################################################################################
  23. if __name__ == '__main__':
  24. print ehtml(
  25. '“Gross national happiness is more important”', 'utf-8'
  26. )
  27. print ehtml('&&', 'utf-8')
  28. ################################################################################