簡體   English   中英

使用其他映射文本文件替換文本文件中的字符串的 Python 代碼

[英]Python code to replace strings in a text file using using other mapping text file

由於它們的結構發生了很大變化,我需要替換我的 sql 代碼中的許多字符串。 我還有其他帶有映射的文件,我需要用它來替換這些字符串。

假設這是我需要替換值的示例代碼文本(當然實際上代碼是數百行):

select * from xyz.def
where line_chart in
('abc12345','cde23456','fgh34567','ijk45678','lmn56789')

和映射文本:

abc12345:bbb222
cde23456:ddd333
fgh34567:fff444
ijk45678:hhh555
lmn56789:jjj666

最好的方法是什么? 感謝你們。

如果有人需要這個,我想通了:

mapping = open(path, 'r')
data_dict = {}
for line in mapping:
    k, v = line.strip().split(':')
    data_dict[k.strip()] = v.strip()


code_file = open(path2, "r")
tempstr = code_file.read()
code_file.close()


def replace_words(base_text, device_values):
    for key, val in device_values.items():
        base_text = base_text.replace(key, val)
    return base_text


output = replace_words(tempstr, data_dict)


file_out = open(path3, 'w')
file_out.write(output)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM