Это моя первая попытка сделать что-то полезное с кодом. У меня есть текстовый файл со строками, которые нужно заменить. Я хочу принять форматированный многострочный stdin, где каждая строка состоит из слова, которое нужно заменить, и его замены.
Содержание текстового документа:
@HOSTNAME@
@INT_LB_IPV4@
Форматированный stdin:
@HOSTNAME@ hostname
@INT_LB_IPV4@ loopback_ipv4_addr
Я дошел до того, что могу действовать в первой строке со следующим кодом, но мне нужно, чтобы он перебирал все пары словарных ключей словаря. Что мне не хватает?
import fileinput
from sys import argv
list = []
#reference text file from stdin
script, TEMPLATEFILE = argv
#prompt for formatted text
print("Enter/Paste your content. Ctrl-D to save it.")
#add formatted text to list
while True:
try:
line = input()
except EOFError:
break
list.append(line)
#convert list to dictionary
dict = {i.split()[0]:(i.split()[1]) for i in list}
#fail to replace string matching key with string matching value in text file
for k, v in dict.items():
with fileinput.input(TEMPLATEFILE, inplace=True, backup='.bak.txt') as TEMPLATEFILE:
for word in TEMPLATEFILE:
print(word.replace(k, v), end='')
Спасибо, что посмотрели.
Здесь решение:
#!/usr/bin/env python3
import fileinput
from sys import argv
#open a file called from stdin and name it templatefile
script, templatefile = argv
#add multi-line content from stdin to a list
list = []
print("Paste content from the spreadsheet. Ctrl-D to save it.")
while True:
try:
line = input()
except EOFError:
break
list.append(line)
#break each line of the list into key-value pairs in a dictionary
dict = {kv.split()[0]:(kv.split()[1]) for kv in list}
#copy into a file named for the hostname value and modify its contents
#replacing words matching dict keys with values
filename = dict.get("@HOSTNAME@")
with open(filename, 'w') as out:
for line in open(templatefile):
for k, v in dict.items():
line = line.replace(k, v)
out.write(line)
#notify of completion with the contents printed to stdout
print("-----\n\nThe file", '"'+filename+'"', "has been created with the following contents:\n")
with open(filename, 'r') as fin:
print(fin.read())