替换字符串循环中的字符

时间:2018-03-20 12:23:37

标签: python python-3.x python-2.7

我有一个模板txt文件。此txt文件将被写为10个新文件,但每个文件都根据任意值列表更改了一些字符:

with open('template.txt') as template_file:
     template = template_file.readlines()
     for i in range(10):
          with open('output_%s.txt' % i, 'w') as new_file:
               new_file.writelines(template_file)

列表的长度与新文件的数量(10)相同。

我正在尝试用我列表中的值替换每个新文件的第二行的一部分。

所以例如,我想要第2行,每个新文件中的位置[5:16]被替换为列表中的相应值。

文件0将包含列表的元素0 文件1将具有列表的元素1 等。

我尝试使用replace()方法:

list = [element0, element1, etc...element9]

for i in template_file:
    i.replace(template_file[2][5:16], list_element)

但它只会用第一个列表元素替换所有文件......它不会循环。

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

我可以找到一些阻止您的代码工作的问题:

  • 您应该写出template,这是一个行列表,而不是template_file,它是一个文件对象
  • 在Python中,字符串是不可变的,这意味着它们无法更改。 replace函数不会更改字符串,它会返回字符串的新副本。此外,replace将用新文本替换子字符串,而不管子字符串在哪里。如果你想在特定索引处替换,我建议你自己切换字符串。例如:

    line2 = '0123456789ABCDEFG'
    element = '-ho-ho-ho-'
    line2 = line2[:5] + element + line2[16:]
    # line2 now is '01234-ho-ho-ho-G'
    
  • 请不要将list用作变量名称。它是一种类型,可用于构建新列表:

    empty = list()         # ==> []
    letters = list('abc')  # ==> ['a', 'b', 'c']
    
  • 表达式template_file[2][5:16]不正确:首先,它应该是template,而不是template_file。其次,第二行应为template[1],而不是template[2],因为Python列表为零

  • list_element变量未在您的代码中声明

解决方案1 ​​

话虽这么说,我发现将模板文件构造为带有占位符的真实模板更容易。我稍后会谈到这个。如果您仍然坚持用某些东西替换第2行的索引5-16,这是我测试的解决方案,它可以工作:

with open('template.txt') as template_file:
    template = template_file.readlines()
    elements = ['ABC', 'DEF', 'GHI', 'JKL']
    for i, element in enumerate(elements):
        with open('output_%02d.txt' % i, 'w') as out_file:
            line2 = template[1]
            line2 = line2[:5] + element + line2[16:]
            for line_number, line in enumerate(template, 1):
                if line_number == 2:
                    line = line2
                out_file.write(line)

注释

  • 代码写出所有行,但特殊替换适用于第2行
  • 代码很笨重,深深嵌套
  • 我不喜欢硬编码索引号(5,16),因为如果模板发生变化,我也必须更改代码

解决方案2

如果你能控制模板文件,我建议使用string.Template类来简化搜索和替换。由于我不知道您的模板文件是什么样的,我将构建自己的模板文件:

line #1
This is my ${token} to be replaced
line #3
line #4

请注意,我打算将${token}替换为代码中的一个元素。现在转到代码:

import string

with open('template.txt') as template_file:
    template = string.Template(template_file.read())
    elements = ['ABC', 'DEF', 'GHI', 'JKL']
    for i, element in enumerate(elements):
        with open('output_%02d.txt' % i, 'w') as out_file:
            out_file.write(template.substitute(token=element))

注释

  • 我用template_file.read()一次阅读整个文件。如果模板文件很大,这可能是一个问题,但之前的解决方案遇到了与此相同的性能问题
  • 我使用string.Template类来简化搜索/替换
  • 搜索和替换由substitute(token=element)完成,其中说:用$token替换${token}中的所有templateelement个实例。
  • 代码更清晰,我敢说,更容易阅读。

解决方案3

如果模板文件太大而无法一次装入内存,您可以修改第一个解决方案,逐行读取,而不是一次读取所有行。我不会在这里提出这个解决方案,只是一个暗示。

答案 1 :(得分:0)

看起来你需要

list = [element0, element1, etc...element9]
for i in list:
    template_file = template_file.replace(template_file[2][5:16], i)
相关问题