1

我有一个看起来像这样的整数列表:

我 = [1020 1022 ....]

我需要打开一个存储为 .txt 的 xml 文件,其中每个条目都包括

Settings="Keys1029"/>

我需要遍历记录,用列表条目替换“Keys1029”中的每个数字。这样就不必:

....Settings="Keys1029"/>
....Settings="Keys1029"/>

我们有:

....Settings="Keys1020"/>
....Settings="Keys1022"/>

到目前为止,我有:

import os
out =   [1020,1022]
with open('c:\xml1.txt') as f1,open('c:\somefile.txt',"w") as f2:
    #somefile.txt is temporary file
    text = f1.read()
    for item in out:
        text = text.replace("Keys1029","Keys"+str(item),1)
    f2.write(text)
#rename that temporary file to real file
os.rename('c:\somefile.txt','c:\xml1.txt')

这是替换:

....Settings="Keys1029"/>
....Settings="Keys1029"/>

....Settings="Keys1"/>
....Settings="Keys1"/>

知道我做错了什么吗?

先感谢您,

4

1 回答 1

1

我会建议一种不同且更强大的算法:

text = """
bla bla bla 1029 and 1029
bla bla bla 1029
bla bla bla 1029 and 1029
"""
out = [1020,1022]
cnt_repl=0
while True:
    text_new = text.replace("1029", str(out[cnt_repl%(len(out))]),1)
    if text_new==text: break
    cnt_repl+=1
    text=text_new
print text

对于它返回的示例文本:

bla bla bla 1020 and 1022
bla bla bla 1020
bla bla bla 1022 and 1020
于 2013-05-18T17:21:15.703 回答