gpt4 book ai didi

Python3 - 将字典嵌套到 JSON

转载 作者:行者123 更新时间:2023-12-01 07:52:44 32 4
gpt4 key购买 nike

我正在尝试将多个 .txt 文件转换为“类似表格”的数据(包含列和行)。每个 .txt 文件应被视为一个新列。

考虑 .txt 文件的以下内容:

File1.txt

Hi there
How are you doing?

What is your name?

File2.txt

Hi
Great!

Oliver, what's yours?

我创建了一个简单的方法,它接受文件和整数(来自另一个方法的文件编号):

def txtFileToJson(text_file, column):

data = defaultdict(list)

i = int(1)
with open(text_file) as f:

data[column].append(column)

for line in f:
i = i + 1
for line in re.split(r'[\n\r]+', line):
data[column] = line

with open("output.txt", 'a+') as f:
f.write(json.dumps(data))

因此上述方法将运行两次(每个文件运行一次,并附加数据)。

这是我运行脚本后的output.txt 文件:

{"1": "What is your name?"}{"2": "Oliver, what's yours?"}

如您所见,我只能让它为我拥有的每个文件创建一个新文件,然后添加整行。

[{
"1": [{
"1": "Hi there",
"2": "How are you doing?",
"3": "\n"
"4": "What is your name?"
},
"2": [{
"1": "Hi"
"2": "Great!",
"3": "\n",
"4": "Oliver, what's yours?"
},
}]

更新:

好的,所以我玩了一下并且更接近了一点:

myDict = {str(column): []}
i = int(1)
with open(text_file) as f:
for line in f:
# data[column].append(column)
match = re.split(r'[\n\r]+', line)
if match:
myDict[str(column)].append({str(i): line})
i = i + 1

with open(out_file, 'a+') as f:
f.write(json.dumps(myDict[str(column)]))

这给了我以下输出:

[{"1": "Hi there\n"}, {"2": "How are you doing?\n"}, {"3": "\n"}, {"4": "What is your name?"}]
[{"1": "Hi\n"}, {"2": "Great!\n"}, {"3": "\n"}, {"4": "Oliver, what's yours?"}]

但如您所见,现在我有多个 JSON 根元素。

解决方案

感谢 jonyfries,我做到了:

 data = defaultdict(list)

for path in images.values():
column = column + 1

data[str(column)] = txtFileToJson(path, column)

saveJsonFile(path, data)

然后添加了一个新方法来保存最终的组合列表:

def saveJsonFile(text_file, data):

basename = os.path.splitext(os.path.basename(text_file))
dir_name = os.path.dirname(text_file) + "/"
text_file = dir_name + basename[0] + "1.txt"

out_file = dir_name + 'table_data.txt'

with open(out_file, 'a+') as f:
f.write(json.dumps(data))

最佳答案

您正在函数本身内创建一个新字典。因此,每次您在其中传递一个文本文件时,都会创建一个新字典。

最简单的解决方案似乎是返回创建的字典并将其添加到现有字典中。

def txtFileToJson(text_file, column):
myDict = {str(column): []}
i = int(1)
with open(text_file) as f:
for line in f:
# data[column].append(column)
match = re.split(r'[\n\r]+', line)
if match:
myDict[str(column)].append({str(i): line})
i = i + 1

with open(out_file, 'a+') as f:
f.write(json.dumps(myDict[str(column)]))

return myDict

data = defaultdict(list)

data["1"] = txtFileToJson(text_file, column)
data["2"] = txtFileToJson(other_text_file, other_column)

关于Python3 - 将字典嵌套到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56117927/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com