使用正则表达式查找句子中的xml部分

2024-10-03 11:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一句话:

<bpt i="1" type="1" x="1" />und ZF-Getriebe <ept i="1" />TipMatic <ph x="2" type="2" />Lite (&lt;/cf&gt;6AS850, 6AS800, 6AS1000)

我想要一个正则表达式,它将提取xml部分,因此最后的句子将是:

__xml__und ZF-Getriebe __xml__TipMatic __xml__Lite (&lt;/cf&gt;6AS850, 6AS800, 6AS1000)

可能的正则表达式是什么


Tags: ltgttypexmllitephcf句子
2条回答

我不认为有什么好的方法可以做到这一点——好吧,正则表达式在提取XML方面不是很好。您最好的选择可能是使用BeautifulSoup:

from bs2 import BeautifulSoup as BS
xml ="""
 <bpt i="1" type="1" x="1" />und ZF-Getriebe <ept i="1" />TipMatic <ph x="2" type="2" />Lite (&lt;/cf&gt;6AS850, 6AS800, 6AS1000)
 """
 a = BS(xml)
 list(a.strings)
 [u'und ZF-Getriebe ', u'TipMatic ', u'Lite (</cf>6AS850, 6AS800, 6AS1000)\n']

您也可以通过以下方式浏览列表

 # It adds <html><body> in front of it, so this gets around that
 cl = list(a.children.next().children.next().children)
 cl
 [<bpt i="1" type="1" x="1"></bpt>,
 u'und ZF-Getriebe ',
 <ept i="1"></ept>,
 u'TipMatic ',
 <ph type="2" x="2"></ph>,
 u'Lite (</cf>6AS850, 6AS800, 6AS1000)\n']

您可以检查每个子项的类型,看看它是字符串还是XML

假设xml标记总是打开-关闭的,这可能会满足您的需要。您仍需要将xml放入

>>> line = '''<bpt i="1" type="1" x="1" />und ZF-Getriebe <ept i="1" />TipMatic <ph x="2" type="2" />Lite (&lt;/cf&gt;6AS850, 6AS800, 6AS1000)'''
>>> import re
>>> pieces = []
>>> pos = 0
>>> for m in re.finditer(r'(<[^\/]+\/>)', line):
...     line[m.span()[0]:m.span()[1]]
...     pieces.append(line[pos:m.span()[0]])
...     pos = m.span()[1]
...     
'<bpt i="1" type="1" x="1" />'
'<ept i="1" />'
'<ph x="2" type="2" />'
>>> pieces.append(line[m.span()[1]:])
>>> pieces
['', 'und ZF-Getriebe ', 'TipMatic ', 'Lite (&lt;/cf&gt;6AS850, 6AS800, 6AS1000)']

相关问题 更多 >