【问题标题】:JSON output is putting all lines in one lineJSON 输出将所有行放在一行中
【发布时间】: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


【解决方案1】:

JSON works 就是这样。它不会根据宽度拆分您的文本,因为 literal newline in string in JSON is illegal. (换行符总是会被转义。)

您应该在文本编辑器中打开自动换行。如果你真的想把行拆分成多行,你可以使用数组。

替换:

new_line_removed =remove_line_one.strip().replace('\n', ',')

与:

new_line_removed =remove_line_one.strip().split('\n')

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多