使用python

时间:2017-04-25 12:36:36

标签: python

我希望python读取文本文件并创建嵌套的dict。 我在文本文件abc中有这些数据。

  

'name':'a','age':11,'blood group':'A + ve','mob num':123456,   '地址':'12,abc street'

     

'name':'b','age':12,'blood group':'A-ve','mob num':124,   '地址':'112,abc street'

我已阅读文本文件,但我不知道如何继续。我是python的初学者。

with open ("text.txt",'r') as f:
    for line in f:
        print line

我的输出应该是

  

{姓名:a,b年龄:11,12 {血型:A + ve,A -ve {Mob num:123456,124   {地址:12 abc street,112 abc street}}}}

2 个答案:

答案 0 :(得分:1)

此代码允许您将每一行作为字典写入列表:

dicts_from_file = []
with open ("text.txt",'r') as f:
    for row in f:
        row = "{" + row + "}"
        dicts_from_file.append(eval(row))
    print dicts_from_file

然后遍历每个字典写入主词典:

master_dict = {}
for dict in dicts_from_file:
    for x in dictionary:
        if x in master_dict:
            master_dict[x].append(dictionary[x])
        else:
            master_dict[x] = [dictionary[x]]
print(master_dict)

这也没有地址问题。

修改

Data_Structure = {"姓名":[],"年龄":[],"其他":{"血型": [],更多:{" Mob num":[],"地址":[]}}}}

说我想写第三个嵌套词典(Mob Number)你会说Data_Structure ["其他"] ["更多"] [" Mob num&#34 ;]追加(' 040010909&#39)。原始语法没有意义,因为你必须为每个子字典都有一个键。

最终编辑

这里有一些代码可以向您展示密钥的匹配是如何工作的。它不是超级优雅但它有效:

some_dict = {"name": [], "age": [],  "other": {"mob num":[],"address":[]}}

with open("hello.txt", 'r') as input_file:
    for row in input_file:
        row = "{" + row + "}"
        this_rows_dict = eval(row)
        for key in this_rows_dict:
            if key == 'name':
                some_dict['name'].append(this_rows_dict[key])
            elif key == 'age':
                some_dict['age'].append(this_rows_dict[key])
            elif key == 'mob num':
                some_dict["other"]["mob num"].append(this_rows_dict[key])
            elif key == "address":
                some_dict["other"]["address"].append(this_rows_dict[key])
            else:
                print("Unknown Key: {}".format(key))
print some_dict

答案 1 :(得分:0)

我希望这可能足以让你开始:

$ var=$(echo -e 'field one☥field two hello☥field three yes moin\nfield 1☥field 2☥field 3 dsdds aq')

$ for i in "$var"; do echo "$i"; done
field one☥field two hello☥field three yes moin
field 1☥field 2☥field 3 dsdds aq

$ echo "$var" | awk -F '☥' '{print $3}'
field three yes moin
field 3 dsdds aq

$ var=$(echo "$var"|sed -E "s/(field one)☥(.+)☥(.+)/\1☥test☥\3/")
$ echo "$var"
field one☥test☥field three yes moin
field 1☥field 2☥field 3 dsdds aq