首页 > 解决方案 > 将参数替换为语句

问题描述

我正在阅读一个大小约为 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'

所以对于每个查询(在此处选择)都有我想要替换的参数。($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 中做到这一点。我正在考虑从参数(line2)创建一个有序字典。然后读取第 1 行中的每个单词以及字典替换中的 key(word) 是否存在值。

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

标签: pythonpostgresql

解决方案


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

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


推荐阅读