如何从文件中每行的第三个字进行字典输入

问题描述 投票:-2回答:1

我有一个文本文件,我想在python中使用字典数据结构将所有带aaa的行归为一组,然后发送到一个名为aaa_file的文件中,并与bbb做同样的事情。

hey student1 aaa 123 yes
hi student2 bbb 321 yes
hello student3 aaa 432 no
hi student4 bbb 589 yes

我想在python中使用字典数据结构将所有带aaa的行归为一组,然后发送到一个名为aaa_file的文件中,并对bbb做同样的事情。

我试过的代码。

import json
import sys

with open("text.txt", 'r') as f:
   lines = f.readlines

newDict{}

for line in lines    
    unit = line.split()    
    newDict[unit[2]]=unit[0:]
print(json.dumps(newDict, indent = 4))
python dictionary key key-value
1个回答
0
投票

这段代码将帮助你

import json
import sys
from collections import defaultdict

with open("text.txt", 'r') as f:
   lines = f.readlines()[1:]

newDict = defaultdict(list)

for line in lines:
    print(line)
    unit = line.split(" ")
    newDict[unit[2]].append(unit)
print(json.dumps(newDict, indent = 4))
for key in newDict:    
    with open("{}_list.json".format(key), "w") as f:
        for i in newDict[key]:
            f.write(" ".join(i) + "\n")

产量

   {
    "aaa": [
        [
            "hey",
            "student1",
            "aaa",
            "123",
            "yes"
        ],
        [
            "hello",
            "student3",
            "aaa",
            "432",
            "no"
        ]
    ],
    "bbb": [
        [
            "hi",
            "student2",
            "bbb",
            "321",
            "yes"
        ],
        [
            "hi",
            "student4",
            "bbb",
            "589",
            "yes"
        ]
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.