Better Unicode Text Wrapping Function


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # This recipe refers:
  2. #
  3. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
  4.  
  5. import re
  6. rx=re.compile(u\"([\\u2e80-\\uffff])\", re.UNICODE)
  7.  
  8. def cjkwrap(text, width, encoding=\"utf8\"):
  9. return reduce(lambda line, word, width=width: \'%s%s%s\' %
  10. (line,
  11. [\' \',\'\\n\', \'\'][(len(line)-line.rfind(\'\\n\')-1
  12. + len(word.split(\'\\n\',1)[0] ) >= width) or
  13. line[-1:] == \'\\0\' and 2],
  14. word),
  15. rx.sub(r\'\\1\\0 \', unicode(text,encoding)).split(\' \')
  16. ).replace(\'\\0\', \'\').encode(encoding)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.