разбиение черезчур длинных слов, по возможности по небуквам

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def wordwrap(text, length=50):
"""
>>> wordwrap('The.Twelve.Kingdoms.14.Shadow.of.the.Moon.Sea.of.the.Shadow.Shadow.of.the.Moon,.Sea.of.the.Shadow.Chapter.of.Recollection.mkv')
'The.Twelve.Kingdoms.14.Shadow.of.the.Moon.Sea.of .the.Shadow.Shadow.of.the.Moon,.Sea.of.the.Shadow .Chapter.of.Recollection.mkv'
>>> wordwrap('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa'
>>> wordwrap('1234567890'*10 + ',blah blah blah' )
'12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890,blah blah blah'
"""
sep = re.compile(r'.{1,%d}$|.{1,%d}\W|.{1,%d}' % (length, length, length), re.M | re.U)
return " ".join(" ".join(sep.findall(word)) for word in text.split(' '))