我无法弄清楚如何用& lt,& gt符号分割这一行:
"<c#><winforms><type-conversion><decimal><opacity>"
我想从以上一行获得以下列表:
['c#', 'winforms', 'type-conversion', 'decimal', 'opacity']
到目前为止我尝试过的是re.split,但没有运气:
>>> re.split("<(\w+?)>", "<c#><winforms><type-conversion><decimal><opacity>")
['<c#>', 'winforms', '<type-conversion>', 'decimal', '', 'opacity', '']
提前致谢!
答案 0 :(得分:2)
如果我们对输入字符串的一些假设是正确的,我们可以一起避免使用正则表达式。我的假设是&#34;列&#34;是xml转义符合此表单的字符串:<col1><col2>...<coln>
。如果是这种情况,那么我们真的不需要<
(所以我们将其删除),我们就可以分开>
。
>>> s = "<c#><winforms><type-conversion><decimal><opacity>"
>>> s.replace('<', '').split('>')
['c#', 'winforms', 'type-conversion', 'decimal', 'opacity', '']
这会在列表的末尾留下一个空字符串,但只需在处理过程中跳过即可切片或处理。
答案 1 :(得分:1)
split()
或re.split()
的解决方案可能更受欢迎,但这里有一个替代方案,而不是在实践中使用它&#34;涉及使用HTML解析器的方法:
>>> from bs4 import BeautifulSoup
>>> from HTMLParser import HTMLParser
>>>
>>> s = "<c#><winforms><type-conversion><decimal><opacity>"
>>> [tag.name for tag in BeautifulSoup(HTMLParser().unescape(s), "html.parser").find_all()]
[u'c#', u'winforms', u'type-conversion', u'decimal', u'opacity']
答案 2 :(得分:1)
为什么要使用拆分,它只使用正则表达式进行开始/结束剪切&#39; n粘贴 切掉中间人,它更快。
使用像这样的正则表达式的findall类函数 (如果跨越行,则设置 dot-all 修饰符)
((?:(?!&[gl]t;).)+)(?:&[gl]t;)*
或者,如果您仍然需要使用拆分使用此正则表达式
(?:&[gl]t;)+
答案 3 :(得分:0)
您可以使用:
[s for s in re.split("<|>", str) if s]
返回:
'c#', 'winforms', 'type-conversion', 'decimal', 'opacity']