Python - 如何使用数组中的值进行逐行替换

时间:2014-04-16 15:51:05

标签: python for-loop xml-parsing

我目前有一个解析文件的Python脚本(在本例中是一个XML文件),并根据需要逐行替换,具体取决于多个数组的值。现在它的脚本效果很好,但感觉它可能会好很多。我还需要稍后添加更多数组,并担心性能。

此外,我目前设置它的方式不允许计算和打印已经完成的总替换。 (例如“替换:xyz - 制作XX替换”)虽然不是直接要求,但我希望将来添加此功能。

我非常感谢任何建议!

以下是代码:

arrayOne = ["old string one", "new string one"]
arrayTwo = ["old string two", "new string two"]

# Variable 'path' collected from command line input
f = open(path, "r", encoding="utf8")
newFile = open(path.replace(".xml", "-new.xml"), "w", encoding="utf8")

def replace(a,b):
    for data in f:
        for datatype in (arrayOne, arrayTwo):
            data = data.replace(datatype[a], datatype[b])
        newFile.write(data)
    newFile.close()

replace(0,1)

f.close()

1 个答案:

答案 0 :(得分:0)

我认为它看起来相当有效,虽然有点令人困惑。我说用一堆数组试一试,看看性能是否有问题。如果你有大量的数组并且必须像现在一样列出它们,它可能会变得混乱。就我个人而言,我认为我将它们全部放在一本大词典中,用#34;旧字符串"是关键。这就是我在下面所做的。

至于你最后的打印行,我认为通过计数器可以很容易,如下所示。

此外,正如现在所说的那样,我认为你不需要replace成为一个单独的职能,除非你计划让它做一些更复杂的事情。

myDictionary = {'old string one' : 'new string one',
                'old string two' : 'new string two'}

# Variable 'path' collected from command line input
f = open(path, "r", encoding="utf8")
newFile = open(path.replace(".xml", "-new.xml"), "w", encoding="utf8")
counter = 0

for data in f:
    for key in myDictionary:
        if key in data:
            data = data.replace(key, myDictionary[key])
            counter += 1
    newFile.write(data)
newFile.close()

f.close()

print 'Replaced', path, 'Made', counter, 'replacements.'