[英]String breaks on square bracket when parsed with lxml
我是lxml解析的新手,無法管理簡單的解析問題。 我的xml中的一行看起來像:
The IgM BCR is essential for survival of peripheral B cells [<xref ref-type="bibr" rid="CR34">34</xref>]. In the absence of BTK B cell...
所以,當我執行以下代碼時:
e = open('somexml.xml', encoding='utf8')
tree = etree.parse(e)
titles = tree.xpath('/pmc-articleset/article/front/article-meta/title-group/article-title')
for node in titles:
text = tree.xpath('/pmc-articleset/article/body/sec/p')
for node in text:
content = str(node.text).encode("utf-8")
s = str(' '.join(lxml.html.fromstring(content).xpath("//text()")).encode('latin1'))
print (s)
結果如下:
The IgM BCR is essential for survival of peripheral B cells ['
即使我只打印node.text而沒有任何“join”命令,結果看起來也很相似。
如何跳過方括號部分並收到完整的字符串? 任何幫助將不勝感激!
]. In the absence of BTK B cell...
]. In the absence of BTK B cell...
是<xref>
元素的tail
屬性的值。 請參閱http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html 。
方括號沒有什么特別之處; 他們只是人物。
使用itertext()
您可以獲取元素及其后代的文本內容。 tail
內容默認包含在內。 請參閱http://lxml.de/api/lxml.etree._Element-class.html#itertext 。
小演示:
from lxml import etree
xml = "<p>TEXT <xref>34</xref>TAIL</p>"
p = etree.fromstring(xml)
print(p.text)
print(''.join(p.itertext()))
print(p.text + p.find("xref").tail)
輸出:
TEXT
TEXT 34TAIL
TEXT TAIL
嘗試這些方面的東西:
e = open('somexml.xml', encoding='utf8')
tree = etree.parse(e)
titles = tree.xpath('/pmc-articleset/article/front/article-meta/title-group/article-title')
for title in titles:
ps = title.xpath('/pmc-articleset/article/body/sec/p')
for p in ps:
text = ''.join(p.itertext())
print(text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.