python - 将参数替换为语句
问题描述
我正在阅读一个大小约为 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) 是否存在值。
肯定有比这更简单的方法。寻找想法。
解决方案
您可以创建一个包含映射列表的字典,其中键是您要搜索和替换的值,值是您希望将找到的键替换为的值:
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
推荐阅读
- ansible - 如何在此任务中使用“列表”变量
- loops - 从过滤的数据中循环遍历每一行
- awk - 如何在最后一场比赛后打印第 6 行到第 10 行?
- android - Redis 发布/订阅认证
- flutter - 问题:RenderFlex 底部溢出 187 个像素
- python - Python(最小)点集之间的大圆距离
- r - 使用 dbplyr 来自 SQL 的数据帧会导致错误。将数据帧写入csv并读取不会导致错误
- scala - 无法使用 JDBC 连接连接到 Hive 服务器
- javascript - 尝试使用机器人令牌获取频道历史记录时出现 missing_scope 错误
- php - Wordpress:函数名必须是字符串