如何从字符串中提取键和值

时间:2019-07-16 08:41:10

标签: regex python-3.x string

我想从字符串中提取一些键及其值。 该程序似乎需要使用正则表达式,但我不太了解

该程序似乎需要使用正则表达式,但我不太了解

字符串是这样的

adprod_type^B6^Apr_flag^B0^Asource^B^Asource_id^B^Aadprod_params^Bheight^D^Chtml^D<style>img{width:100% !important; height:100% !important}</style>\\n<script>gAdController.passback();</script>^Cwidth^D^Aadprodset_id^B9123^Aadserve^B

期望是这样

adprod_type:'6',pr_flag:'0',source:'',source_id:'',adprod_params:{height:'',html:'<style>img{width:100% !important; height:100% !important}</style>\\n<script>gAdController.passback();</script>',width:''},adprodset_id:'9123',adserve:''

我尝试过这个:

file_obj = open("/Users/icko/Documents/000/a.txt")
all_lines = file_obj.readlines()
for line in all_lines:
    a = line.split('^A')
    for i in a:
        b = i.split('^B')
        key = b[0]
        val = b[1]
        data[key] = val
    if data['adprod_type'] == '6':
        print('key=' + key)
        print('value=' + val)
file_obj.close()

谢谢

1 个答案:

答案 0 :(得分:0)

我尝试过:

if __name__ == '__main__':

    file_obj = open("/Users/icko/Documents/000/a.txt")
    all_lines = file_obj.readlines()
    for line in all_lines:
        data = {}
        a = line.split('')
        for i in a:
            b = i.split('')
            key = b[0]
            val = b[1]
            data[key] = val
        if data['adprod_type'] == '6':
            metadata = {}
            metadata1 = {}
            metadata2 = {}
            metadata3 = {}

            subdata = data['adprod_params']
            c = subdata.split('')
            data1 = c[0].split('')
            data2 = c[1].split('')
            data3 = c[2].split('')
            key1 = data1[0]
            key2 = data2[0]
            key3 = data3[0]
            val1 = data1[1]
            val2 = data2[1]
            val3 = data3[1]
            metadata1[key1] = val1
            metadata2[key2] = val2
            metadata3[key3] = val3
            metadata = dict(metadata1, **metadata2, **metadata3)
            print(metadata)

成功!