2013-02-04 114 views
0

在Python讀取下一行,比如我解碼網址,找到這樣一份報告:找到一條線,在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()方法來定位的地方我有意思,閱讀下一行進一步編程? 基本上如何找到一個特定的行,並閱讀我剛剛發現的行下的下一行?

謝謝。

回答

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

0
def getLine(source, string): 
    source = source.split('\n') 
    for index, item in enumerate(source): 
     if string in item: 
      return source[index + 1] 
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