有趣的运动。。。
以下内容有点复杂,不会给你所指示的确切输出,但可能它足够接近,你(或其他人)可以修改它:
from lxml import etree
stuff = """[your xml]"""
doc = etree.XML(stuff)
#we need this in order to count how many <li> elements meet the condition
#in your xml there are only two, but this will take care of more elements
comms = len(doc.xpath('//p[contains(.,":")]//ul//li'))
final = []
for t in doc.xpath('//*'):
line = "".join(list(t.itertext()))
allin = [l.strip() for l in line.split('\n ') if len(l.strip())>0]
for l in allin:
ind = allin.index(l)
for c in range(comms):
if ":" in allin[ind-(c+1)]:
final.append("- "+l)
if l[-1] =="." or l[-1] ==":":
final.append(l)
else:
if not ("- "+l in final):
final.append(l+".")
break
final
输出:
['This is a title.',
'This is a first paragraph.',
'This is a second paragraph. With a list:',
'- first item',
'- second item',
'And the end.',
'This is a third paragraph.',
'This is a first long sentence.',
'This is a second long sentence.',
'And the end of the paragraph.']