gpt4 book ai didi

python - 在 Python 中 - 解析响应 xml 并找到特定的文本值

转载 作者:IT王子 更新时间:2023-10-28 23:34:12 27 4
gpt4 key购买 nike

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

关于python - 在 Python 中 - 解析响应 xml 并找到特定的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7668204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com