简体   繁体   中英

Python3 - Using dictionary key-value pairs to search and replace strings in a file

This is my first ever attempt at doing something useful with code. I have a text file with strings that need to be replaced. I want to accept formatted multiline stdin where each line is composed of the word to be replaced and its replacement.

Text document contents:

@HOSTNAME@
@INT_LB_IPV4@

Formatted stdin:

@HOSTNAME@    hostname
@INT_LB_IPV4@    loopback_ipv4_addr

I've gotten to the point where I can act on the first line with the following code, but I need it to iterate across all of the dictionary key-value pairs. What am I missing?

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='')

Thanks for looking.

Here's the solution:

#!/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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM