简体   繁体   English

如何使功能重复

[英]How to make a function repeat itself

I have a python problem, I'm reading from XML and have two spread functions set up; 我有一个python问题,我正在阅读XML,并设置了两个传播函数; one finds a location, than the other function finds a location inside the first one, and returns info. 一个找到一个位置,然后另一个函数找到第一个内部的位置,然后返回信息。 my problem is that i need this to continue down the page and find other occurrences of each. 我的问题是,我需要这样做才能继续浏览该页面并查找每个其他出现的事件。 I'm not sure if thats a good explanation of now so heres code: 我不确定这是否是一个很好的解释,所以这里的代码:

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)

so need it to do the functions again to get another earthquake and print out the hole list of them. 因此需要再次执行该功能以再次发生地震并打印出它们的孔清单。 please help! 请帮忙! thanks 谢谢

Don't try and parse XML manually. 不要尝试手动解析XML。 There are plenty of good ways of doing it, including ElementTree in the standard library. 有很多好的方法,包括标准库中的ElementTree

lxml.etree makes this nice to work with. lxml.etree使它很好用。

For an XML document structured as so: 对于这样构造的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>

You can use lxml.etree like this to parse it: 您可以使用lxml.etree这样来解析它:

from lxml import etree

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

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

(from the example at http://lxml.de/tutorial.html ) (摘自http://lxml.de/tutorial.html的示例)

The result looks like this: 结果看起来像这样:

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

Season to taste! 季节品尝!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM