public
Created

Dictionary-based HTML hyphenation using soft hyphen

  • Download Gist
hyphenation.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import os
import re
 
from htmlentitydefs import name2codepoint
 
# Must install the `hyphenator` library from PyPi!
from hyphenator import Hyphenator
 
# Firefox comes with an English hyphenation dictionary
path = os.popen('locate hyph_en_US.dic').readlines()[0].strip()
 
hyphenator = Hyphenator(path)
spaces = re.compile(r'\s+')
shy = unichr(name2codepoint['shy'])
 
def hyphenate(string, max_length=20):
return " ".join(
len(word) > max_length and
shy.join(
part.rstrip('-') for part in
(hyphenator.wrap(word, max_length) or (word, ))
) or word for word in spaces.split(string.strip()))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.