在Python中查找一行并阅读下一行

时间:2013-02-04 04:43:21

标签: python line

在Python中,例如,我解码网址并找到这样的报告:

<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()找到我感兴趣的地方并阅读下一行进一步编程? 基本上如何找到一个特定的行并阅读我刚发现的行下的下一行?

感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 parsing

答案 2 :(得分:0)

def getLine(source, string):
    source = source.split('\n')
    for index, item in enumerate(source):
        if string in item:
            return source[index + 1]