0

例如,在 Python 中,我解码一个 url 并找到这样的报告:

<title>Canada Olympic Park</title>

<description>Open  / Past 48 Hours: 0cm / Primary:  / Base Depth: 85cm</description>

<title>Castle Mountain</title>

<description>Open  / Past 48 Hours: 1cm / Primary:  / Base Depth: 179cm</description>

<title>Lake Louise</title>

<description>Open  / Past 48 Hours: 2cm / Primary:  / Base Depth: 162cm</description>

如何使用 find() 找到我感兴趣的地方并阅读下一行以进行进一步编程?基本上如何找到一个特定的行并阅读我刚刚找到的行下的下一行?

谢谢。

4

3 回答 3

1

尝试使用 itertools.dropwhile():

Python 2.7.3 (default, Sep  4 2012, 20:19:03) 
[GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> src="foo\nbar\nbas\n"
>>> notfoundyet=True
>>> def findthing(x):
...     global notfoundyet
...     currently=notfoundyet
...     notfoundyet=x!="bar"
...     return currently
... 
>>> itertools.dropwhile(findthing, src.split("\n"))
<itertools.dropwhile object at 0x8017d92d8>
>>> for x in _: 
...     print x
... 
bas
于 2013-02-04T05:00:35.963 回答
1

您可以使用xml.dom.minidom

假设您的 xml 数据在文件中

from xml.dom.minidom import parse

xmldata = open("abc.txt", "r")

domdata = parse(xmldata)

def getDescriptionData(title):
    titledata = [x.toxml().lstrip('<title>').rstrip('</title>') for x in domdata.getElementsByTagName('title')]
    descriptiondata = [x.toxml().lstrip('<description>').rstrip('</description>') for x in domdata.getElementsByTagName('description')]

    l =  [v for (x, v) in zip(titledata, descriptiondata) if x == title]
    if l:
        return l[0]
    return None

print getDescriptionData('Lake Louis')

输出:

Open  / Past 48 Hours: 2cm / Primary:  / Base Depth: 162cm

您还可以查看SAX XML 解析

于 2013-02-04T05:12:16.893 回答
0
def getLine(source, string):
    source = source.split('\n')
    for index, item in enumerate(source):
        if string in item:
            return source[index + 1]
于 2013-02-04T04:47:59.853 回答