【问题标题】:Python3 - Using dictionary key-value pairs to search and replace strings in a filePython3 - 使用字典键值对搜索和替换文件中的字符串
【发布时间】:2018-11-24 14:27:56
【问题描述】:

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

文本文档内容:

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

感谢收看。

【问题讨论】:

  • 建议将您的代码格式化为单个代码块,并以 cmets 进行解释。更容易阅读,读者可以直接复制/粘贴到编辑器中查看发生了什么。
  • 仔细阅读您的循环:对于每个单词/替换对,您打开一个文件,然后替换该单词的出现。你从第一个单词开始,处理整个文件,然后是下一个单词(再次处理整个文件),下一个单词等等——这肯定不是你想要的。
  • 谢谢帕特里克。现在我要做的就是弄清楚如何不这样做。
  • 为什么不将first ever尝试分成两个独立但可以工作的部分:一个可测试的函数,它确实替换了字符串中的某些内容,以及一个在用户输入时运行此函数的接口。我认为立即将两者结合到一个脚本中是一个相当困难的开始。
  • 也许我咬的比我能嚼的多。我有一个小东西可以找到并替换,这是我将它与多行输入集成的尝试。它比原来的要大得多。

标签: python file dictionary replace find


【解决方案1】:

解决办法如下:

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

【讨论】: