如何让一个函数重复执行

0 投票
2 回答
1696 浏览
提问于 2025-04-16 12:46

我遇到了一个Python的问题,我正在从XML文件中读取数据,并设置了两个函数。第一个函数用来找到一个位置,第二个函数则在第一个位置里面再找一个位置,并返回相关信息。我的问题是,我需要这个过程继续进行,去找到页面上其他的相同内容。我不确定这样解释是否清楚,所以这里有代码:

def findEntryTag(webPage):
 start= webPage.find("<entry>") +7
 end= webPage.find("</entry>")
 slicedString=webPage[start:end]
 return slicedString

def findEarthquake(webPage):
 slicedString=findEntryTag(webPage)
 start= slicedString.find("<title>") +7
 end= slicedString.find("</title>")
 eq= slicedString[start:end]
 return eq

my Earthquake= findEarthquake(text)
print (myEarthquake)

所以我需要让这些函数再次运行,以获取另一个地震信息,并打印出所有的列表。请帮帮我!谢谢!

2 个回答

5

别试着手动解析XML文件。其实有很多简单好用的方法可以做到这一点,比如标准库里的ElementTree

1

lxml.etree 让处理这个变得很简单。

对于一个结构如下的 XML 文档:

<entry>
    <title>story 1</title>
    <text>this is the first earthquake story</text>
    <title>story 2</title>
    <text>this is the second earthquake story</text>
    <title>story 3</title>
    <text>this is the third earthquake story</text>
</entry>

你可以这样使用 lxml.etree 来解析它:

from lxml import etree

root = etree.parse("test.xml")

for element in root.iter("title"):
    print("%s - %s" % (element.tag, element.text))

(这个例子来自 http://lxml.de/tutorial.html

结果看起来是这样的:

title - story 1
title - story 2 
title - story 3

根据个人口味调整!

撰写回答