0

我有一个如下的xml文件

<?xml version="1.0" encoding="utf-8"?>
<myTable xmlns="http://schemas.microsoft.com/windows/2008">
  <my id="1">Hi this is one</my>
  <my id="2">Hi this is one</my>
  <my id="6">Hi this is one</my> 
  <my id="7">Hi this is one</my>
   <my id="8">Hi this is one</my>
   <my id="9">Hi this is one</my>
</myTable>

我想将(1)附加到第一个'my id =“1”'。这样我的结果xml将如下所示

<?xml version="1.0" encoding="utf-8"?>
<myTable xmlns="http://schemas.microsoft.com/windows/2008">
  <my id="1">Hi this is one(1)</my>
  <my id="2">Hi this is one</my>
  <my id="6">Hi this is one</my> 
  <my id="7">Hi this is one</my>
   <my id="8">Hi this is one</my>
   <my id="9">Hi this is one</my>
 </myTable>

我希望这件事在 python 正则表达式中完成

谢谢

4

2 回答 2

0

import re

r = re.compile(r'(<my id="1">.*)(</my>)')

with open(infilename, 'r') as infile, open(newfile, 'w+') as outfile:
    for line in infile:
        match = r.search(line)
        if match:
            f.write(match.group(1) + '(1)' + match.group(2))
        else:
            f.write(line)

你想要什么?

这将搜索具有给定模式的行,如果它们匹配,则获取它们的内容并在其间插入一些东西。

于 2012-12-12T15:44:56.683 回答
-1

创建一个新文件可以吗?如果是这样,那么:

import re

f = open(newfile, 'w+')

for line in open(your_file, 'r');
  match = re.search(r'id="1"', line)
  if match:
    f.write('<my id="1">Hi this is one(1)</my>')
  else:
    f.write(line)

f.close()
于 2012-12-12T15:40:10.303 回答