Python3 - 使用字典键值对搜索和替换文件中的字符串



这是我第一次尝试用代码做一些有用的事情。 我有一个文本文件,其中包含需要替换的字符串。 我想接受格式化的多行标准,其中每行都由要替换的单词及其替换组成。

文本文档内容:

@HOSTNAME@
@INT_LB_IPV4@

格式化标准:

@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("-----nnThe file", '"'+filename+'"', "has been created with the following contents:n")
with open(filename, 'r') as fin:
print(fin.read())

最新更新