如何从文件中每行的第三个单词创建字典条目
How to make dictionary entry from third word of each line in a file
我有一个文本文件:
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))
这段代码会帮助你
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"
]
]
}
我有一个文本文件:
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))
这段代码会帮助你
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"
]
]
}