在Python中-解析响应xml并查找特定的文本vau

2024-10-01 02:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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都没有成功,我已经到了一个我不知道还能做什么的地步。

任何帮助都将不胜感激


Tags: 文档importdatafootitleparse情况xml
3条回答

这有帮助吗。。。

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

就我所知,这很简单:

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'))

如果您只是想计算一个单词在XML文档中出现的次数,只需将该文档作为字符串读取并进行计数:

import urllib2
data = urllib2.urlopen('http://www.example.com/file.xml').read()
print data.count('foobar')

否则,您只需遍历要查找的标记即可:

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

相关问题 更多 >