首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将txt文件数据解析为结构化JSON文件

如何将txt文件数据解析为结构化JSON文件
EN

Stack Overflow用户
提问于 2019-03-13 07:39:57
回答 1查看 665关注 0票数 -2

我有一个很大的文本文件,它的结构如下:

代码语言:javascript
复制
    2018-12-02

    Blue: 25 lux
    Green: 7 lux
    Red: 16 lux
    Blue: 25 lux
    Green: 7 lux
    Red: 16 lux
    Blue: 25 lux
    Green: 7 lux
    Red: 16 lux
    Blue: 24 lux

    .....

    avgBlue: 29.80 lux
    avgGreen: 8.40 lux
    avgRed: 19.40 lux

当我尝试获取json文件的这种格式时,我在正确解析该文件时遇到了问题。

代码语言:javascript
复制
{  
   "Date":{  
      "2017-11-02":[  
         {  
            "Blue":"25 lux",
            "Green":"7 lux",
            "Red":"16 lux"
         },
         {  
            "Blue":"25 lux",
            "Green":"7 lux",
            "Red":"16 lux"
         },
         {  
            "Averages":{  
               "avgBlue":"29.80 lux",
               "avgGreen":"8.40 lux",
               "avgRed":"19.40 lux"
            }
         }
      ]
   }
}

但我甚至不确定我将如何着手制作这个脚本。任何帮助都将不胜感激,因为我不熟悉python。

EN

回答 1

Stack Overflow用户

发布于 2019-03-13 07:59:30

首先,您需要将文本文件转换为字典。使用json库将字典转换为json文件非常容易,但在此之前,我们必须读取文件。

在这里,似乎最简单的方法是使用有限状态机。本质上,一次读一行,并根据需要迭代地添加到我们的字典中,这取决于我们刚刚读到的内容。

代码语言:javascript
复制
my_file = open('my_file.txt', 'r')
state = 0                           # Initialize our program's state
my_dict = {"Date": {}}              # Initialize the dict we're putting everything in
for line in my_file:
    if len(line.strip()) == 0:
        continue                    # skip blank lines
    if state == 0:
        # we're expecting a date on this line
        current_date = line.strip()
        my_dict["Date"][current_date] = []  # Initialize this date in the dict
        state = 1
    elif state == 1:
        # we're expecting a Blue or an avgBlue
        if line.find('avg') == 0:
            # we found 'avg', so we're looking for avgBlue
            value = line.split(':')[-1].strip()  # get the string after the ':'
            my_dict["Date"][current_date].append({"Averages":{"avgBlue": value}})
            state = 4
        elif line.find('Blue') == 0:
            # we found 'Blue'
            value = line.split(':')[-1].strip() 
            my_dict["Date"][current_date].append({"Blue": value})
            state = 2
        else:
            # we start a new date or something
            ...
    elif state == 2:
        # we're expecting a Green
        value = line.split(':')[-1].strip()
        my_dict["Date"][current_date][-1]["Green"] = value
        state = 3
    elif state == 3:
        # we're expecting a Red
        value = line.split(':')[-1].strip()
        my_dict["Date"][current_date][-1]["Red"] = value
        state = 1
    elif state == 4:
        ...

my_file.close()

老实说,这是一个相当复杂的结构,但是由于您的输入文件不是易于解析的格式,您可能或多或少会受到它的限制。我不会实现整个代码,您可能需要重写其中的大部分代码才能处理特定的输入文件,但这应该是一个起点。无论如何,有限状态机是计算机科学中最基本的原则之一,因此值得学习。

在字典中实际获得输入后,将其输出为json非常简单:

代码语言:javascript
复制
import json
with open('my_json.json', 'w') as json_file:
    json_file.write(json.dumps(my_dict))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55132279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档