我是 python 新手,在使用 xml 和 python 时遇到特别困难。我遇到的情况是这样的,我正在尝试计算一个单词在 xml 文档中出现的次数。很简单,但是 xml 文档是来自服务器的响应。是否可以在不写入文件的情况下执行此操作?尝试凭记忆来做这件事会很棒。
下面是一个示例 xml 代码:
<xml>
<title>Info</title>
<foo>aldfj</foo>
<data>Text I want to count</data>
</xml>
这是我在 python 中的内容
import urllib2
import StringIO
import xml.dom.minidom
from xml.etree.ElementTree import parse
usock = urllib.urlopen('http://www.example.com/file.xml')
xmldoc = minidom.parse(usock)
print xmldoc.toxml()
过去,我尝试过使用 StringIO、ElementTree 和 minidom,但都没有成功,而且我已经到了不知道还能做什么的地步。
任何帮助将不胜感激
据我所知,这很简单:
import urllib2
from xml.dom import minidom
usock = urllib2.urlopen('http://www.example.com/file.xml')
xmldoc = minidom.parse(usock)
for element in xmldoc.getElementsByTagName('data'):
print element.firstChild.nodeValue
因此,要计算字符串的出现次数,请尝试以下操作(有点简洁,但我喜欢单行代码):
count = sum(element.firstChild.nodeValue.find('substring') for element in xmldoc.getElementsByTagName('data'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)