Python多次替换匹配

时间:2016-11-23 13:40:14

标签: python-2.x

正在进行的Json2yaml转换器用于Ansible(http://docs.ansible.com/ansible/ec2_group_module.html)创建

项目链接: https://github.com/shdobxr/json2yamlAnsible/blob/master/json2yaml.py

回答!见上面的项目。

我一直在堆栈上研究这个。而且它不是点击。

Python replace multiple strings

这是我的尝试,请善待我过去曾涉猎python。生锈在这里显示:

#!/usr/local/bin/python

import re, sys, json, yaml

with open(sys.argv[1]) as f:
#   print yaml.safe_dump(json.load(f), default_flow_style=False)
   a = yaml.safe_dump(json.load(f), default_flow_style=False)

c = sys.argv[1] + ".yml"

text_file = open(c, "w")
text_file.write(a)
text_file.close

replacements = {
    '    ToPort:': '            to_port:',
    '  - FromPort:': '            from_port:',
    'UserIdGroupPairs:': '',
    'Vpc:': '',
    'VpcPeeringConnectionId:': '',
    'UserIdGroupPairs:': '',
    'PrefixListIds: []': '',
    '- Description:': '        description:',
    '  GroupName:': '    - name:',
    '  -     IpProtocol:': '          - proto:',
    '- Description:': '        description:',
    'SecurityGroups:': '- name:',
    '  IpPermissions:': '        rules:',
    '  IpPermissionsEgress:': '        rules_egress:',
    '  GroupId:': '',
    '    - GroupId:': '            group_id:'
}


replacements = dict((re.escape(k), v) for k, v in replacements.iteritems())
#pattern = re.compile('|'.join(replacements.keys()))

remove_pattern = re.compile('|'.join(k for k, v in replacements.iteritems() if v is None))
replace_pattern = re.compile('|'.join(k for k, v in replacements.iteritems() if v is not None))


def rewrite(text):
    if remove_pattern.search(text):
        return ''
    return replace_pattern.sub(lambda m: replacements[re.escape(m.group())], text)


with open(c, 'rt') as fin:
    with open('out.txt', 'wt') as fout:
        for line in fin:
            fout.write(rewrite(line))

测试文件(将其另存为test.json)

{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "PrefixListIds": [],
                    "FromPort": 22,
                    "IpRanges": [
                        {
                            "CidrIp": "10.0.0.0/24"
                        }
                    ],
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": [
                        {
                            "UserId": "XXXXXXXXXXXX",
                            "GroupId": "sg-xxxxxxxx"
                        }
                    ]
                },
                {
                    "PrefixListIds": [],
                    "FromPort": 3389,
                    "IpRanges": [
                        {
                            "CidrIp": "10.0.0.0/24"
                        }
                    ],
                    "ToPort": 3389,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": [
                        {
                            "UserId": "XXXXXXXXXXXX",
                            "GroupId": "sg-xxxxxxxx"
                        }
                    ]
                }
            ],
            "Description": "TEST JSON",
            "Tags": [
                {
                    "Value": "Test JSON",
                    "Key": "Name"
                }
            ],
            "IpPermissions": [
                {
                    "PrefixListIds": [],
                    "FromPort": 22,
                    "IpRanges": [
                        {
                            "CidrIp": "10.0.0.0/24"
                        }
                    ],
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": [
                        {
                            "UserId": "XXXXXXXXXXXX",
                            "GroupId": "sg-xxxxxxxx"
                        }
                    ]
                },
                {
                    "PrefixListIds": [],
                    "FromPort": 3389,
                    "IpRanges": [
                        {
                            "CidrIp": "10.0.0.0/24"
                        }
                    ],
                    "ToPort": 3389,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": [
                        {
                            "UserId": "XXXXXXXXXXXX",
                            "GroupId": "sg-xxxxxxxx"
                        }
                    ]
                }
            ],
            "GroupName": "Test JSON",
            "VpcId": "vpc-XXXXXXXX",
            "OwnerId": "XXXXXXXXXXXX",
            "GroupId": "sg-xxxxxxxx"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

您引用的答案适合您的用例:

import re

replacements = {
    'ToPort': 'to_port',
    'FromPort': None
}
replacements = dict((re.escape(k), v) for k, v in replacements.iteritems())
remove_pattern = re.compile('|'.join(
                    k for k, v in replacements.iteritems() if v is None))
replace_pattern = re.compile('|'.join(
                    k for k, v in replacements.iteritems() if v is not None))


def rewrite(text):
    if remove_pattern.search(text):
        return ''
    return replace_pattern.sub(
                lambda m: replacements[re.escape(m.group())], text)


with open('in.txt', 'rt') as fin:
    with open('out.txt', 'wt') as fout:
        for line in fin:
            fout.write(rewrite(line))