Ticket #1919: truncate.py

File truncate.py, 2.5 KB (added by Chris Beaven, 17 years ago)
Line 
1from django.utils.text import truncate_words
2
3import re
4re_space = re.compile(r'(?:^\s+)?\S+\s*')
5def new_truncate_words(s, num):
6 "Truncates a string after a certain number of words."
7 length = int(num)
8 words = []
9 for count, match in enumerate(re_space.finditer(s)):
10 if count >= length: # count is 0-based
11 if words:
12 last_word = words[-1].rstrip()
13 words[-1] = last_word
14 if not last_word.endswith('...'):
15 words.append(' ...')
16 break
17 words.append(match.group())
18 return ''.join(words)
19
20
21import time
22
23loop = range(100000)
24short = 'test me out now'
25longer = '''Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque eget lacus non leo euismod accumsan. Ut lorem. Curabitur vehicula egestas enim. Nunc pretium egestas orci. Donec est dolor, luctus et, condimentum in, luctus non, nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam ultricies tempus ligula. Morbi vitae enim. Nunc pulvinar gravida purus. Duis lorem nulla, hendrerit sit amet, sollicitudin vel, accumsan non, leo. Maecenas eleifend nisl eu turpis. Praesent tempus neque sit amet metus. Vivamus auctor quam vitae metus fringilla placerat. Proin tincidunt lacus id leo.
26
27Curabitur eget nulla quis massa interdum tristique. Maecenas metus mauris, interdum id, consectetuer et, sollicitudin sit amet, lectus. Duis commodo pede vitae neque. Cras ut ligula in massa feugiat ultrices. In consectetuer risus at nibh. Pellentesque eget purus. Vivamus porta dapibus massa. Quisque et enim. Nunc cursus enim eu nibh. Cras iaculis, lacus quis consectetuer interdum, turpis orci dapibus neque, ac pellentesque nisi elit at ante. Etiam faucibus. Mauris dolor. Vivamus id quam ut sapien porta ornare. Maecenas arcu est, pharetra et, ornare quis, sodales ac, ante.'''
28
29print 'truncate_words: ', truncate_words(short, 3)
30print 'new_truncate_words:', new_truncate_words(short, 3)
31
32start = time.clock()
33for i in loop:
34 truncate_words(short, 3)
35print 'short truncate_words ', time.clock() - start
36
37start = time.clock()
38for i in loop:
39 new_truncate_words(short, 3)
40print 'short new_truncate_words', time.clock() - start
41
42
43start = time.clock()
44for i in loop:
45 truncate_words(longer, 3)
46print 'long truncate_words ', time.clock() - start
47
48start = time.clock()
49for i in loop:
50 new_truncate_words(longer, 3)
51print 'long new_truncate_words', time.clock() - start
Back to Top