Jas*_*son 9 python xml memory parsing
我是python的新手,我在使用xml和python时遇到了特别困难.我的情况是这样,我试图计算一个单词出现在xml文档中的次数.很简单,但xml文档是来自服务器的响应.是否可以在不写入文件的情况下执行此操作?尝试从记忆中做到这一点会很棒.
这是一个示例xml代码:
<xml>
<title>Info</title>
<foo>aldfj</foo>
<data>Text I want to count</data>
</xml>
Run Code Online (Sandbox Code Playgroud)
这是我在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()
Run Code Online (Sandbox Code Playgroud)
过去这一点我尝试使用StringIO,ElementTree和minidom没有成功,我已经到了一个点,我不知道还能做什么.
任何帮助将不胜感激
如果您只是想计算一个单词在 XML 文档中出现的次数,只需将文档作为字符串读取并进行计数:
import urllib2
data = urllib2.urlopen('http://www.example.com/file.xml').read()
print data.count('foobar')
Run Code Online (Sandbox Code Playgroud)
否则,您可以遍历您要查找的标签:
from xml.etree import cElementTree as ET
xml = ET.fromstring(urllib2.urlopen('http://www.example.com/file.xml').read())
for data in xml.getiterator('data'):
# do something with
data.text
Run Code Online (Sandbox Code Playgroud)
据我所知,这很简单:
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
Run Code Online (Sandbox Code Playgroud)
所以要计算一个字符串的出现次数,试试这个(有点浓缩,但我喜欢单行):
count = sum(element.firstChild.nodeValue.find('substring') for element in xmldoc.getElementsByTagName('data'))
Run Code Online (Sandbox Code Playgroud)
这有帮助吗...
from xml.etree.ElementTree import XML
txt = """<xml>
<title>Info</title>
<foo>aldfj</foo>
<data>Text I want to count</data>
</xml>"""
# this will give us the contents of the data tag.
data = XML(txt).find("data").text
# ... so here we could do whatever we want
print data
Run Code Online (Sandbox Code Playgroud)