我越来越有以下matter.Let的发言权麻烦匹配,我有两个列表中的某些字符串在词典:字符串在python
left right
british 7
cuneate nucleus Medulla oblongata
Motoneurons anterior
而且我有一个文件像下面的一些测试线:
<s id="69-7">British Meanwhile is the studio 7 album by british pop band 10cc 7.</s>
<s id="5239778-2">Medulla oblongata,the name refers collectively to the cuneate nucleus and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, motoneurons located in the spinal.</s>
我想输出像下面的样子:
<s id="69-7"><w2>British</w2> Meanwhile is the studio <w2>7</w2> album by <w1>british</w1> pop band 10cc <w2>7</w2>.</s>
<s id="5239778-2"><w2>Medulla oblongata</w2>,the name refers collectively to the <w1>cuneate nucleus</w1> and gracile nucleus, which are present at the junction between the spinal cord and the <w2>medulla oblongata</w2>.</s>
我试着用下面的代码:
import re
def textReturn(left, right):
text = ""
filetext = open(text.xml, "r").read()
linelist = re.split(u'[\n|\r\n]+',filetext)
for i in linelist:
left = left.strip()
right = right.strip()
if left in i and right in i:
i1 = re.sub('(?i)(\s+)(%s)(\s+)'%left, '\\1<w1>\\2</w1>\\3', i)
i2 = re.sub('(?i)(\s+)(%s)(\s+)'%right, '\\1<w2>\\2</w2>\\3', i1)
text = text + i2 + "\n"
return text
但它给我:
'<s id="69-7">British meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc 7.</s>'.
<s id="5239778-2">Medulla oblongata,the name refers collectively to the <w1>cuneate nucleus</w1> and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, <w1>motoneurons</w2> located in the spinal.</s>
即如果有开头&端线,不能标记。
此外,我只是想得到返回这些行,其中匹配左&右字符串,而不是其他行。
任何解决方案,请!非常感谢!!!
该输入看起来像XML。你确定你不需要用XML解析器拉出字符串吗?此外,RE真的应该使用原始字符串(r'...'),因为它们不会专门处理反斜杠。 – Keith
Keith有一个好点。依靠整个'''元素在一条线上可能不是一个好主意。如果考虑字面字符串,CDATA部分,处理指令等,只能自己找到元素,但为什么当xml解析器已经为你做了这些工作?有一个学习曲线来使用它们,以及XSLT(用于按照你想要的方式修改文档),但它是如此值得! –