我有一个包含一些内容的xml树,我想计算有多少树元素有一个特定的关键字。以下是xml结构
<tree>
<tw>
<con>Bla bla bla</con>
</tw>
<tw>
<con>Bla bla bla bla bla</con>
</tw>
...
</tree>
这是我写的函数。我使用的是python2.7。你知道吗
def conta_una(tree, kw1):
conta=[]
for i, tw in enumerate(tree.findall('tw')):
for con in tw.findall('con'):
if con.text and kw1 in con.text:
conta.append(tw.getchildren())
print(len(conta))
然后在python中导入函数,定义两个变量并调用函数
from xml.etree.ElementTree import ElementTree
tr1 = ElementTree().parse('/path/file.xml')
keyword = "word"
conta_una(tr1, keyword)
不管我在变量keyword
中输入什么关键字,我总是得到1作为结果。但是如果我像这样显式地编写函数
tree = ElementTree().parse('/path/file.xml')
conta=[]
for i, tw in enumerate(tree.findall('tw')):
for con in tw.findall('con'):
if con.text and "word" in con.text:
conta.append(tw.getchildren())
print(len(conta))
我得到了正确的结果。我肯定我在函数定义上犯了一个非常愚蠢的错误,但我不明白是什么,甚至看了手册。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐