2016-05-13 3 views
0

Я хотел вставить reverse_html в качестве первого элемента footnote до footnote.text, но не смог.Вставка элемента в начале текста

Как я могу это сделать?

#!/usr/bin/env python3 

from unittest import TestCase, TestProgram 

class T(TestCase): 
    def test(self): 
     try: 
      from lxml.etree import fromstring, tostring, XMLParser 
     except ImportError: 
      raise 
     p_start = r'<p id="n1">' 
     p_text = r'description' 
     p_end = r'</p>' 
     p = p_start + p_text + p_end 
     a = r'<a href="#r1">^</a>' 
     parser = XMLParser(remove_blank_text=True) 
     footnote, reverse_href = (fromstring(xml, parser) for xml in (p, a)) 
     self._transform(footnote, reverse_href) 
     expected = self._expected(p_start, p_text, p_end, a) 
     gotten = tostring(footnote).strip().decode() 
     self.assertEqual(expected, gotten) 
    @staticmethod 
    def _transform(footnote, reverse_href): 
     footnote.text = ' ' + footnote.text 
     footnote.insert(0, reverse_href) 
    @staticmethod 
    def _expected(p_start, p_text, p_end, a): 
     return p_start + a + ' ' + p_text + p_end 

if __name__ == r'__main__': 
    TestProgram() 

ответ

0

"Я хотел вставить reverse_html в качестве первого элемента footnote перед тем footnote.text"

В lxml.etree модели, что означает переход footnote.text быть tail из reverse_html:

def _transform(footnote, reverse_href): 
    reverse_href.tail = footnote.text 
    footnote.text = '' 
    footnote.insert(0, reverse_href) 

Результат:

>>> print etree.tostring(footnote).strip().decode() 
<p id="n1"><a href="#r1">^</a>description</p> 
Смежные вопросы