【发布时间】:2011-07-31 18:17:43
【问题描述】:
我遇到了以下问题。假设我在字典的两个列表中有一些字符串:
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'...'),因为它们不会特别处理反斜杠..
-
基思有一个很好的观点。将整个
s元素放在一行上可能不是一个好主意。如果您考虑到文字字符串、CDATA 部分、处理指令等,您只能自己寻找元素,但是当 xml 解析器已经为您这样做时,您为什么还要这样做呢?使用它们以及 XSLT(用于以您想要的方式修改文档)有一个学习曲线,但它非常值得!