mirror of https://github.com/django/django.git
Vastly improved performance of django.utils.text.wrap. Thanks to GvR for the impetus and Micael Radziej for the patch.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4213 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
35f7e33b4a
commit
5efb9272e2
|
@ -8,17 +8,28 @@ capfirst = lambda x: x and x[0].upper() + x[1:]
|
||||||
def wrap(text, width):
|
def wrap(text, width):
|
||||||
"""
|
"""
|
||||||
A word-wrap function that preserves existing line breaks and most spaces in
|
A word-wrap function that preserves existing line breaks and most spaces in
|
||||||
the text. Expects that existing line breaks are posix newlines (\n).
|
the text. Expects that existing line breaks are posix newlines.
|
||||||
See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
|
|
||||||
"""
|
"""
|
||||||
return reduce(lambda line, word, width=width: '%s%s%s' %
|
def _generator():
|
||||||
(line,
|
it = iter(text.split(' '))
|
||||||
' \n'[(len(line[line.rfind('\n')+1:])
|
word = it.next()
|
||||||
+ len(word.split('\n',1)[0]
|
yield word
|
||||||
) >= width)],
|
pos = len(word) - word.rfind('\n') - 1
|
||||||
word),
|
for word in it:
|
||||||
text.split(' ')
|
if "\n" in word:
|
||||||
)
|
lines = word.splitlines()
|
||||||
|
else:
|
||||||
|
lines = (word,)
|
||||||
|
pos += len(lines[0]) + 1
|
||||||
|
if pos > width:
|
||||||
|
yield '\n'
|
||||||
|
pos = len(lines[-1])
|
||||||
|
else:
|
||||||
|
yield ' '
|
||||||
|
if len(lines) > 1:
|
||||||
|
pos = len(lines[-1])
|
||||||
|
yield word
|
||||||
|
return "".join(_generator())
|
||||||
|
|
||||||
def truncate_words(s, num):
|
def truncate_words(s, num):
|
||||||
"Truncates a string after a certain number of words."
|
"Truncates a string after a certain number of words."
|
||||||
|
|
Loading…
Reference in New Issue