2013-04-24 40 views
3

我正在通過一個看起來像這樣的OPML文件進行搜索。我想拉出輪廓文本和xmlUrl。如何使用正則表達式在OPML(XML)文件中查找引用的屬性值

<outline text="lol"> 
    <outline text="Discourse on the Otter" xmlUrl="http://discourseontheotter.tumblr.com/rss" htmlUrl="http://discourseontheotter.tumblr.com/"/> 
    <outline text="fedoras of okc" xmlUrl="http://fedorasofokc.tumblr.com/rss" htmlUrl="http://fedorasofokc.tumblr.com/"/> 
    </outline> 

我的功能:

import re 
rssName = 'outline text="(.*?)"' 
rssUrl = 'xmlUrl="(.*?)"' 

def rssSearch(): 
    doc = open('ttrss.txt') 
    for line in doc: 
     if "xmlUrl" in line: 
      mName = re.search(rssName, line) 
      mUrl = re.search(rssUrl, line) 
      if mName is not None: 
       print mName.group() 
       print mUrl.group() 

然而,返回值出來爲:

outline text="fedoras of okc" 
xmlUrl="http://fedorasofokc.tumblr.com/rss" 

什麼是rssName和rssUrl適當的正則表達式,我只返回字符串引號之間?

+0

相當無關你的問題,但也許還是有幫助的:你可以預編譯正則表達式來節省一些納秒的執行時間。使用rssName = re.compile('outline text =「(。*?)」')'和'mName = rssName.search(line)'。 – kay 2013-04-24 20:29:21

+3

爲什麼你想通過正則表達式來做到這一點?這不是正確的工具。使用一個XML解析器,標準庫中有幾個。 – 2013-04-24 20:31:06

+0

關於@ DanielRoseman的建議,如果你想要的東西容易使用,包括廚房水槽,看看美麗的石頭湯,美麗的湯庫的XML解析組件。 – Endophage 2013-04-24 20:34:39

回答

3

不要使用正則表達式解析XML。代碼很混亂,可能出錯的東西太多了。

例如,如果你的OPML提供商恰好重新格式化輸出這樣的:

<outline text="lol"> 
    <outline 
     htmlUrl="http://discourseontheotter.tumblr.com/" 
     xmlUrl="http://discourseontheotter.tumblr.com/rss" 
     text="Discourse on the Otter" 
    /> 
    <outline 
     htmlUrl="http://fedorasofokc.tumblr.com/" 
     xmlUrl="http://fedorasofokc.tumblr.com/rss" 
     text="fedoras of okc" 
    /> 
</outline> 

這是完全有效的,這意味着同樣的事情。但是面向行的搜索和正則表達式如'outline text="(.*?)"'將會中斷。

而是使用XML解析器。您的代碼將是更清潔,更簡單,更可靠:

import xml.etree.cElementTree as ET 

root = ET.parse('ttrss.txt').getroot() 
for outline in root.iter('outline'): 
    text = outline.get('text') 
    xmlUrl = outline.get('xmlUrl') 
    if text and xmlUrl: 
     print text 
     print xmlUrl 

這同時處理你的OPML片段,我喜歡這個political science list在網絡上發現了類似的OPML文件。這很簡單,沒有什麼棘手的。 (我不是吹牛,這只是您使用XML解析器,而不是正則表達式得到好處。)

2

嘗試

print mName.group(1) 
print mUrl.group(1) 

http://docs.python.org/2/library/re.html#re.MatchObject.group

如果groupN參數爲0,相應的返回值是整個匹配的字符串;如果它在包含範圍[1..99]中,則它是匹配相應括號組的字符串。

rssName = 'outline text="(?P<text>.*?)"' 

然後

print mName.group('text') 
+0

謝謝! 1在這裏表示什麼,它是如何解決這個問題的? – jumbopap 2013-04-24 20:31:43

+1

我編輯過這篇文章,查看一下:) – nacholibre 2013-04-24 20:35:02

相關問題