[英]Python3 - Using dictionary key-value pairs to search and replace strings in a file
這是我第一次嘗試對代碼進行有用的操作。 我有一個文本文件,其中的字符串需要替換。 我想接受格式化的多行標准輸入,其中每行由要替換的單詞及其替換組成。
文字文件內容:
@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("-----\n\nThe file", '"'+filename+'"', "has been created with the following contents:\n")
with open(filename, 'r') as fin:
print(fin.read())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.