我正在提取xml文档中的所有文本。我想查找标记saydescription,然后搜索所有子代和孙代,可能还有更多元素,然后提取文本。
这是我的代码,但它无法在孙子标记中获取文本:
for element in root.find('description'):
print 'parent: ', element.tag, '|', element.attrib
try:
data.write(element.text)
for all_tags in element.findall('./'):
print 'child: ', all_tags.tag, '|', all_tags.attrib
if all_tags.text:
data.write('\n')
data.write(all_tags.text)
if all_tags.tail:
data.write('\n')
data.write(all_tags.tail)
data.write('\n')
data.write('\n')
except TypeError:
pass
except UnicodeEncodeError:
unicodestr = element.text.encode("utf-8")
data.write(unicodestr)
data.write('\n')
问题出在for all_tags
循环中。
样本输入:
<description>
<p num="p-0003">
Protein kinases are involved in the signal transduction pathways linking growth factors, hormones and other cell regulation molecules to cell growth, survival and metabolism under both normal and pathological conditions. One such protein kinase, protein kinase B (also known as Akt), is a serine/threonine kinase that plays a central role in promoting the proliferation and survival of a wide range of cell types, thereby protecting cells from apoptosis (programmed cell death) (Khwaja,
<i>Nature</i>
33-34 (1990)). Three members of the Akt/PKB subfamily of second-messenger regulated serine/threonine protein kinases have been identified and are termed Akt1/PKBα, Akt2/PKBβ, and Akt3/PKBγ. A number of proteins involved in cell proliferation and survival have been described as substrates of Akt in cells. Two examples of such substrates include glycogen synthase kinase-3 (GSK3) and Forkhead transcription factors (FKs). See Brazil and Hemmings,
<i>Trends in Biochemical Sciences</i>
26, 675-664.
</p>
<p num="p-0004">
A number of protein kinases and phosphatases regulate the activity of Akt; For instance, activation of Akt is mediated by phosphatidylinositol 3-kinase (PI3-K), which initiates the binding of second messenger phospholipids to the pleckstrin homology (PH) binding domain of Akt. The binding anchors Akt to plasma membrane and results in phosphorylation and activation of the enzyme. Amplifications of the catalytic subunit of PI3-K, p110α, or mutations in the PI3-K regulatory subunit, p85α, lead to activation of Akt in several types of human cancer. (Vivanco and Sawyers,
<i>Nature Reviews in Cancer</i>
(2002) 2: 489-501.
</p>
<p num="p-0005">
The tumor suppressor, PTEN, is a critical negative regulator of Akt activation by PI3-K. Myers et al.
</p>
</description>
在这个输入中,<i> Nature </i>
之后的文本将丢失,并替换为第一行中的文本。我相信这是因为all_tags.tail
从父标记而不是子和孙子标记获取文本。
你可能想使用itertext(),但是如果你想稍微提高你的游戏水平,你应该试试xpath。在这种情况下,它真的会发光。
下面是一个例子-我给出的xpath基本上说:
查找XML文档中任何位置的所有标记,然后返回 它和所有孩子的文本。
element.findall('./')
显式只查找标记的直接子级。查找所有子代的表达式是.//
(双斜杠)。根据给定的示例简化循环,结果是:
或者使用
repr()
来显示字符串文字:相关问题 更多 >
编程相关推荐