开发者

How to make a function repeat itself

I have a python problem, I'm reading from XML and have two spread functions set up; one fi开发者_如何学编程nds 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. There are plenty of good ways of doing it, including ElementTree in the standard library.


lxml.etree makes this nice to work with.

For an XML document structured as so:

<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:

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)

The result looks like this:

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

Season to taste!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜