如何替换任意结构化数据中关键字的所有实例? [英] How to replace all instances of a keyword in arbitrarily structured data?

查看:100
本文介绍了如何替换任意结构化数据中关键字的所有实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在结构复杂的字典中替换kw(例如,值可能是字典或列表.那些字典也应替换其kw,列表元素可能是也应替换的字典.)以下

I want to replace kw's in a dict which may have complex structure (e.g the values may be dicts or lists. Those dicts should also get their kw's replaced and the list elements may be dicts which should also get replaced.) I wrote the following

def replace_kw(obj,replace_this,with_this):
    print('object is '+str(obj))
    if isinstance(obj,dict):
        for k,v in obj.iteritems():
            if k==replace_this:
                obj[with_this]=obj[replace_this]
                del(obj[replace_this])
            else:
                obj[k] = replace_kw(obj[k],replace_this,with_this)
    elif isinstance(obj,list):
        for l in obj:
            l = replace_kw(l,replace_this,with_this)    
    return obj

适用于我熟悉的简单示例,但是我对其他方法以及可能会出错的地方感到好奇.例如,我检查了一个关键字是否可以是一个字典,看来答案是否定的,所以那是我没有出错的地方.

which works on the simple examples I have conme up with but I am curious as to other methods and where this may go wrong. For instance I checked if a keyword can be a dictionary , and it seems the answer is no so that's one place I am not going wrong.

我举的例子是

  d = {'data': [{'bbox_xywh': [838, 533, 50, 68], 'object': 'truck'},
{'bbox_xywh': [930, 563, 60, 57], 'object': 'car'}, 
{'bbox_xywh': [993, 560, 78, 56], 'object': 'car'}, 
{'bbox_xywh': [997, 565, 57, 39], 'object': 'car'}, 
{'bbox_xywh': [1094, 542, 194, 126], 'object': 'car'}, 
{'bbox_xywh': [1311, 539, 36, 74], 'object': 'person'}], 
'dimensions_h_w_c': (1200, 1920, 3), 
'filename':'/data/jeremy/image_dbs/hls/voc_rio_udacity_kitti_insecam_shuf_no_aug_test/1478020901220540088.jpg'}

replace_kw(d,'bbox_xywh','bbox')

{'data': [{'bbox': [838, 533, 50, 68], 'object': 'truck'},
  {'bbox': [930, 563, 60, 57], 'object': 'car'},
  {'bbox': [993, 560, 78, 56], 'object': 'car'},
  {'bbox': [997, 565, 57, 39], 'object': 'car'},
  {'bbox': [1094, 542, 194, 126], 'object': 'car'},
  {'bbox': [1311, 539, 36, 74], 'object': 'person'}],
 'dimensions_h_w_c': (1200, 1920, 3),
 'filename': '/data/jeremy/image_dbs/hls/voc_rio_udacity_kitti_insecam_shuf_no_aug_test/1478020901220540088.jpg'}

按预期工作

推荐答案

json

一种快速简单的解决方案包括使用re.sub使用json将整个对象转换为字符串,然后将其转换回:

json

A quick-n-simple solution involves converting the entire thing to a string with json, using re.sub and then converting it back:

import json, re
json.loads(re.sub('(?<=")bbox_xywh(?=":)', 'bbox', json.dumps(d), flags=re.M))

{'data': [{'bbox': [838, 533, 50, 68], 'object': 'truck'},
  {'bbox': [930, 563, 60, 57], 'object': 'car'},
  {'bbox': [993, 560, 78, 56], 'object': 'car'},
  {'bbox': [997, 565, 57, 39], 'object': 'car'},
  {'bbox': [1094, 542, 194, 126], 'object': 'car'},
  {'bbox': [1311, 539, 36, 74], 'object': 'person'}],
 'dimensions_h_w_c': [1200, 1920, 3],
 'filename': '/data/jeremy/image_dbs/hls/voc_rio_udacity_kitti_insecam_shuf_no_aug_test/1478020901220540088.jpg'}

您也可以考虑使用str.replace代替正则表达式(速度稍快):

You may also consider using str.replace instead of regex (slightly faster):

json.loads(json.dumps(d).replace('"bbox_xywh":', '"bbox":'))

相信json它可以一致地对您的数据进行字符串化处理.您可以像这样处理任意结构的字典.

Have faith in json that it stringifies your data consistently. You can handle dictionarys of arbitrary structure like this.

当您的数据不兼容JSON时,此操作将失败-如果您除了列表和字典或自定义类对象之外还拥有其他python对象,则该对象将不再起作用.

This fails when your data isn't JSON compliant - if you have other python objects besides lists and dicts or custom class objects, this no longer works.

这是使用ast.literal_eval解决上述问题的另一种方法:

Here's another method with ast.literal_eval to overcome the problem mentioned above:

import ast
ast.literal_eval(str(d).replace('\'bbox_xywh\':', '\'bbox\':'))

虽然它不强迫元组到列表,但我不喜欢这样做,因为必须非常谨慎地处理引号.

While it does not coerce tuples to lists, I'm not a fan of this because the quotes have to be treated very carefully.

这篇关于如何替换任意结构化数据中关键字的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆