将参数替换为语句

时间:2018-07-02 17:36:11

标签: python postgresql

我正在读取一个大小约为50gb的巨大日志文件。这是一堆查询和参数。

我已经做了必要的清理,现在日志看起来像一堆

select this_.x as x, this_.y as y, this_.ACTION_ID as ACTION3_291_0_ from table where this_.id=$1 and this_.type=$2 and this_.id=$3
$1 = '4', $2 = 'cleanup', $3 = '2323'

每个查询的SO(在这里选择)有一些我要替换的参数。($ 1,$ 2,$ 3)

所以最终查询将是

select this_.x as x, this_.y as y, this_.ACTION_ID as ACTION3_291_0_ from table where this_.id='4' and this_.type='cleanup' and this_.id='2323'

如何在python中执行此操作。我正在考虑从参数(第2行)创建有序字典。然后读取第1行中的每个单词,如果字典替换中的key(word)是否存在值。

肯定有比这更简单的方法。寻找想法。

1 个答案:

答案 0 :(得分:0)

您可以创建一个包含映射列表的字典,其中的键是要搜索和替换的值,而值是想要用找到的键替换的值:

s = 'select this_.x as x, this_.y as y, this_.ACTION_ID as ACTION3_291_0_ from table where this_.id=$1 and this_.type=$2 and this_.id=$3'

mappings = {
    '$1': '4',
    '$2': 'cleanup',
    '$3': '2323'
}

# Loop through the dictionary, replacing every found occurency of they key with the value
for k, v in mappings.items():
    s = s.replace(k, v)

print(s)
>>> select this_.x as x, this_.y as y, this_.ACTION_ID as ACTION3_291_0_ from table where this_.id=4 and this_.type=cleanup and this_.id=2323