gpt4 book ai didi

python - 如何将文本文件转换为json文件?

转载 作者:行者123 更新时间:2023-12-02 02:19:57 25 4
gpt4 key购买 nike

我是 python 新手,我想将文本文件转换为 json 文件。其外观如下:

#Q Three of these animals hibernate. Which one does not?
^ Sloth
A Mouse
B Sloth
C Frog
D Snake

#Q What is the literal translation of the Greek word Embioptera, which denotes an order of insects, also known as webspinners?
^ Lively wings
A Small wings
B None of these
C Yarn knitter
D Lively wings

#Q There is a separate species of scorpions which have two tails, with a venomous sting on each tail.
^ False
A True
B False

Contd
.
.
.
.

^ 表示答案。

我想要 json 格式,如下所示。示例:

{
"questionBank": [
{
"question": "Grand Central Terminal, Park Avenue, New York is the worlds",
"a": "largest railway station",
"b": "Longest railway station",
"c": "highest railway station",
"d": "busiest railway station",
"answer": "largest railway station"
},
{
"question": "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
"a": "Asia",
"b": "Africa",
"c": "Europe",
"d": "Oceania",
"answer": "Africa"
}, Contd.....
]
}

我遇到过一些类似的帖子,以下是我尝试过的:

dataset = "file.txt"
data = []
with open(dataset) as ds:
for line in ds:
line = line.strip().split(",")
print(line)

输出为:

['']
['#Q What part of their body do the insects from order Archaeognatha use to spring up into the air?']
['^ Tail']
['A Antennae']
['B Front legs']
['C Hind legs']
['D Tail']
['']
['#Q What is the literal translation of the Greek word Embioptera', ' which denotes an order of insects', ' also known as webspinners?']
['^ Lively wings']
['A Small wings']
['B None of these']
['C Yarn knitter']
['D Lively wings']
['']

Contd....

包含逗号的句子由Python列表分隔。我尝试使用 .join 但没有得到我期望的结果。
请让我知道如何解决这个问题。

最佳答案

dataset = "text.txt"
question_bank = []

with open(dataset) as ds:
for i, line in enumerate(ds):
line = line.strip("\n")
if len(line) == 0:
question_bank.append(question)
question = {}
elif line.startswith("#Q"):
question = {"question": line}
elif line.startswith("^"):
question['answer'] = line.split(" ")[1]
else:
key, val = line.split(" ", 1)
question[key] = val
question_bank.append(question)

print({"questionBank":question_bank})

#for storing json file to local directory
final_output = {"questionBank":question_bank}

with open("output.json", "w") as outfile:
outfile.write(json.dumps(final_output, indent=4))

关于python - 如何将文本文件转换为json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66577624/

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