【发布时间】:2021-01-17 14:44:48
【问题描述】:
我想将文本文件转换为 JSON。我遇到的问题是它以某种方式将 txt 文件中的所有行添加到 JSON 中的一个非常长的行中。请帮忙。
import re
import os
import json
# list of files to be sent to Json file
loadfile = open("aivc-tests/baseline/clf_risk_start.txt", "r")
print("Loading file..."
#takes away the extention from name of file
name_of_file = "clf_risk_start"
print("Removing unnecessary items...")
if loadfile.mode == 'r':
contents = loadfile.read()
#remove all unnecessary items
remove_dashes = re.sub("-","", contents)
remove_hashes =re.sub("##", "", remove_dashes)
remove_intent =re.sub("intent", "", remove_hashes)
remove_colan =re.sub(":", "", remove_intent)
remove_generic =re.sub("Generic", "", remove_colan)
remove_critical =re.sub("critical", "", remove_generic)
remove_line_one=re.sub("<! Generated using Chatette v1.6.2 >", "", remove_critical)
new_line_removed =remove_line_one.strip().replace('\n', ',')
edited_contents = new_line_removed
# print(edited_contents)
#return(edited_contents)
print("Formating...")
data1 = {}
data1['clf_test_utterances'] = []
data1['clf_test_utterances'].append({
name_of_file: edited_contents
})
data2 = {}
data2['testing Suit'] = []
data2['testing Suit'].append({
'Name': 'test',
'Description': 'this is just a test',
'Test Dialogue': '',
"format_version": 5,
"clf_test_utterances": data1
})
print("Exporting to json")
# this will write to json file
with open('test_suit_single.json', 'w') as outfile:
json.dump(data2, outfile)
print('successfully converted')
输出就是我下面的内容
{
"testing Suit":[
{
"Name":"test",
"Description":"this is just a test",
"Test Dialogue":"",
"format_version":5,
"clf_test_utterances":{
"clf_test_utterances":[
{
"clf_risk_start":"I am experiencing signs of covid 19. How can I get tested to understand if I i am well as i think?, I am experiencing symptoms of coronvirus. How can I be checked out to verify if I have it or not?, I am feeling signs of corona. How can I be tested to be sure if I I should self isolate?, I am feeling signs of coronvirus. How can I test to learn if I i am healthy?, I am ms of covid 19. How can I "
}
]
}
}
]
}
我怎样才能将它们全部放在不同的行中?
【问题讨论】:
-
为什么会有问题?
-
所以用
indent = 4参数转储它 -
其实看输出,我没看懂问题
-
如果您希望将其拆分为行(在 JSON 中),请考虑使用行数组而不是连接成 str 的行。将
new_line_removed =remove_line_one.strip().replace('\n', ',')替换为new_line_removed =remove_line_one.strip().split('\n') -
您使用
{name_of_file: edited_contents }创建了一个字典,并从edited_contents中删除了所有换行符。那么你希望换行符来自哪里?
标签: python json python-3.x converters