python,列出两个标签之间的所有内容

问题描述

| 我正在寻找最简单的方法来编写该代码。 说我有一个包含以下内容的字符串:
\'the f<ox jumpe>d over the l<azy> dog <and the >fence\'
使用<作为开始标记,并使用>作为结束标记,我想将它们之间的所有内容保存到列表中。 如果保存到list1中,则list1等于[\'ox jumpe \',\'azy \',\'和\'] 谁知道这样做的一种不错的,简洁的SHORT方式。 谢谢!     

解决方法

        正则表达式应该在这里发挥作用:
import re

text = \'the f<ox jumpe>d over the l<azy> dog <and the >fence\'
list = re.findall(\'.*?\\<(.*?)\\>.*?\',text)

print list
编辑: 您可以在此处阅读有关正则表达式的更多信息 主要地,上面的正则表达式的作用是: 。*? -所有字符的非贪婪匹配,直到下一个想要的字符 \\ <-匹配 \”表示标签的开头或结尾,例如你不能有
<hi<there>
x=\"<a><bb><ccc>\"
>>> starts=(i for i,c in enumerate(x) if c==\"<\")
>>> ends=(i for i,c in enumerate(x) if c==\">\")
>>> ans=[x[i+1:j] for i,j in zip(starts,ends)]
>>> ans
[\'a\',\'bb\',\'ccc\']
如果它是一个大的xml文件以节省内存,请使用izip(尽管x [i + 1:j]需要更改,因为您不希望整个文件都为字符串)。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...