1 | from django.utils.text import truncate_words
|
---|
2 |
|
---|
3 | import re
|
---|
4 | re_space = re.compile(r'(?:^\s+)?\S+\s*')
|
---|
5 | def 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 |
|
---|
21 | import time
|
---|
22 |
|
---|
23 | loop = range(100000)
|
---|
24 | short = 'test me out now'
|
---|
25 | longer = '''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 |
|
---|
27 | Curabitur 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 |
|
---|
29 | print 'truncate_words: ', truncate_words(short, 3)
|
---|
30 | print 'new_truncate_words:', new_truncate_words(short, 3)
|
---|
31 |
|
---|
32 | start = time.clock()
|
---|
33 | for i in loop:
|
---|
34 | truncate_words(short, 3)
|
---|
35 | print 'short truncate_words ', time.clock() - start
|
---|
36 |
|
---|
37 | start = time.clock()
|
---|
38 | for i in loop:
|
---|
39 | new_truncate_words(short, 3)
|
---|
40 | print 'short new_truncate_words', time.clock() - start
|
---|
41 |
|
---|
42 |
|
---|
43 | start = time.clock()
|
---|
44 | for i in loop:
|
---|
45 | truncate_words(longer, 3)
|
---|
46 | print 'long truncate_words ', time.clock() - start
|
---|
47 |
|
---|
48 | start = time.clock()
|
---|
49 | for i in loop:
|
---|
50 | new_truncate_words(longer, 3)
|
---|
51 | print 'long new_truncate_words', time.clock() - start
|
---|