我有一个模板文件,当我找到特定字符串时,我会用某些值替换它们。
输入文件
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]的区域。这就是我想要查看其所属部门中每位员工的公司编号的方式。有什么想法吗?
答案 0 :(得分:0)
我会略微调整这个问题的方法。我会将模板分成更大的部分,根据您的可变输入数量构建每个部分,然后将这些部分替换/插入到模板中。
# 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)