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

时间:2018-06-14 18:29:17

标签: python file dictionary replace find

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

文本文档内容:

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

感谢您的光临。

1 个答案:

答案 0 :(得分:0)

这是解决方案:

#!/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())
相关问题