我正在通過一個看起來像這樣的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適當的正則表達式,我只返回字符串引號之間?
相當無關你的問題,但也許還是有幫助的:你可以預編譯正則表達式來節省一些納秒的執行時間。使用rssName = re.compile('outline text =「(。*?)」')'和'mName = rssName.search(line)'。 – kay 2013-04-24 20:29:21
爲什麼你想通過正則表達式來做到這一點?這不是正確的工具。使用一個XML解析器,標準庫中有幾個。 – 2013-04-24 20:31:06
關於@ DanielRoseman的建議,如果你想要的東西容易使用,包括廚房水槽,看看美麗的石頭湯,美麗的湯庫的XML解析組件。 – Endophage 2013-04-24 20:34:39