2012-10-12 122 views
0

我有一个很长的字符串,我试图获得返回一个字符串后发生 另一个字符串。例如,我首先在字符串中查找字符串'zombiesattack',然后查找名为'title'的字符串的第一个地方,并希望打印将'text'保存在'title'和'/ title'之间的文本到名为“titleOfVideo”的另一个变量。我在做这件事上遇到了一些困难。有什么建议?存储在变量命名的数据 如何在一个子字符串发生在另一个字符串之后?

data= <updated>2012-10-10T19:20:55.000Z</updated> 
<abc>zombiesattack</abc> 
<category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video" /> 
<category scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="Sports" label="Sports" /> 
<title>NY Yankees: 6 Essential Pieces of Postseason Memorabilia</title> 

串,我想挽救“纽约洋基:6个季后大事记的基本部分”将变量“titleOfVideo”。

starting_point = data.find('zombiesattack') 
new_string = data[starting_point:] 
title_point = new_string.find('<title>') 
print new_string[:title_point] 

titleOfVideo = new_string[title_point:20] 

当我尝试这个并打印titleOfVideo,我得到了一堆返回线。

+2

使用Python(http://docs.python.org /library/xml.dom.html)而不是试图做一堆手动字符串匹配。 – GWW

+0

我如何使用XML解析器实现这一点?我正在阅读文档,但遇到了麻烦。 – sharataka

回答

0

使用XML解析器来代替,如ElementTree的:建于[XML解析器]

from xml.etree import ElementTree 
# you need a valid xml string 
data = '<root>' + data + '</root>' 
etree = ElementTree.fromstring(data) 
if etree.findtext('abd') == 'zombiesattack': 
    titleOfVideo = etree.findtext('title') 
0

对于这个特定的例子:

starting_point = data.find('zombiesattack') 
new_string = data[starting_point:] 
title_start = new_string.find('<title>') 
title_end = new_string.find('</title>') 
titleOfVideo = new_string[title_start + len('<title>'):title_end] 
相关问题