使用replace()python在文件中重复节
我有一个模板文件,当我找到特定的字符串时,我会用特定的值替换它们 输入文件使用replace()python在文件中重复节,python,templates,output,Python,Templates,Output,我有一个模板文件,当我找到特定的字符串时,我会用特定的值替换它们 输入文件 The following are the names of the company The name is [NAME] -- Company number for each name ( [NAME] Company number [NUMBER] ) Incorporated 我希望输出像这样 The following are the names of the company The name i
The following are the names of the company
The name is [NAME]
--
Company number for each name
( [NAME]
Company number [NUMBER]
)
Incorporated
我希望输出像这样
The following are the names of the company
The name is Julie
The name is Stan
The name is Nick
--
Company number for each name
( Julie
Company number 00
)
( Stan
Company number 02
)
( Nick
Company number 03
)
Incorporated
这是我的python代码
input = open("input.txt")
output = open("output.txt","w")
name=['Julie', 'Stan', 'Nick']
number=['00','02','03']
i = 0
for row in input:
if "[NAME]" in row:
row=row.replace("[NAME]",name[i])
i+=1
output.write(row)
input.close()
output.close()
我想检测一个区域来重复值,比如for循环
[FOR]
...
[/FOR]
其中,如果我检测到[FOR],则遍历该区域并填充所需的[NAME]数量。这就是我想在它自己的部分中查看每个员工的公司编号的方式。有什么想法吗?我会稍微调整一下解决这个问题的方法。我会将模板分成更大的部分,根据可变的输入数量构建每个部分,然后将这些部分替换/插入到模板中
# input.txt
The following are the names of the company
[names_section]
--
Company number for each name
[company_numbers_section]
Incorporated
#script.py
names = ['Julie', 'Stan', 'Nick']
numbers = ['00','02','03']
names_section = ''
for name in names:
names_section += 'The name is {}.\n'.format(name)
company_numbers_section = ''
for name, number in zip(names, numbers):
company_numbers_section += '( {}\n'.format(name)
company_numbers_section += ' Company number {}\n'.format(number)
company_numbers_section += ')\n\n'
template = open('input.txt', 'r').read()
template = template.replace('[names_section]', names_section)
template = template.replace('[company_numbers_section]', company_numbers_section)
with open('output.txt', 'w') as output:
output.write(template)
我会稍微调整解决这个问题的方法。我会将模板分成更大的部分,根据可变的输入数量构建每个部分,然后将这些部分替换/插入到模板中
# input.txt
The following are the names of the company
[names_section]
--
Company number for each name
[company_numbers_section]
Incorporated
#script.py
names = ['Julie', 'Stan', 'Nick']
numbers = ['00','02','03']
names_section = ''
for name in names:
names_section += 'The name is {}.\n'.format(name)
company_numbers_section = ''
for name, number in zip(names, numbers):
company_numbers_section += '( {}\n'.format(name)
company_numbers_section += ' Company number {}\n'.format(number)
company_numbers_section += ')\n\n'
template = open('input.txt', 'r').read()
template = template.replace('[names_section]', names_section)
template = template.replace('[company_numbers_section]', company_numbers_section)
with open('output.txt', 'w') as output:
output.write(template)
我喜欢这个解决方案。但是,我希望用户能够创建模板并决定输出的格式。我喜欢这个解决方案。但是,我希望用户能够创建模板并决定如何格式化输出。