|
0
|
1 |
import uuid |
|
|
2 |
import xml.dom.minidom |
|
|
3 |
import re |
|
|
4 |
from BeautifulSoup import BeautifulSoup, Comment |
|
|
5 |
|
|
|
6 |
|
|
|
7 |
def get_text_nodes(soup): |
|
|
8 |
return soup(text=lambda text:not isinstance(text, Comment)) |
|
|
9 |
|
|
|
10 |
def is_real_text_node(textNode): |
|
|
11 |
return not textNode.findParent('style') |
|
|
12 |
|
|
|
13 |
def get_the_soup(input): |
|
|
14 |
return BeautifulSoup(input, convertEntities=["xml", "html"]) |
|
270
|
15 |
|
|
|
16 |
from cm.utils.cache import memoize, dj_memoize |
|
|
17 |
@dj_memoize |
|
0
|
18 |
def spannify(input): |
|
|
19 |
""" |
|
|
20 |
wrap textNodes in spans |
|
|
21 |
""" |
|
|
22 |
|
|
|
23 |
input = re.sub("\s*$","",input) |
|
|
24 |
|
|
|
25 |
soup = get_the_soup(input) |
|
|
26 |
|
|
|
27 |
textNodes = get_text_nodes(soup) |
|
|
28 |
textNodes_content = [] |
|
|
29 |
|
|
|
30 |
span_starts = {} |
|
|
31 |
for i in xrange(len(textNodes)): |
|
|
32 |
textNode = textNodes[i] |
|
|
33 |
if is_real_text_node(textNode) : |
|
|
34 |
textNode.replaceWith('<span id="sv_' + str(i) + '" class="c-s"><span id="sv-' + str(i) + '" class="c-count-0 c-c">' + textNode.string + '</span></span>') |
|
|
35 |
span_starts[i] = len(''.join(textNodes_content)) |
|
|
36 |
textNodes_content.append(textNode.string) |
|
|
37 |
output = unicode(soup) |
|
|
38 |
|
|
|
39 |
textualized = ''.join(textNodes_content) |
|
|
40 |
return output, textualized, span_starts |