我有一个很大的文本文件,它的结构如下:
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文件的这种格式时,我在正确解析该文件时遇到了问题。
{
"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。
发布于 2019-03-13 07:59:30
首先,您需要将文本文件转换为字典。使用json
库将字典转换为json文件非常容易,但在此之前,我们必须读取文件。
在这里,似乎最简单的方法是使用有限状态机。本质上,一次读一行,并根据需要迭代地添加到我们的字典中,这取决于我们刚刚读到的内容。
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非常简单:
import json
with open('my_json.json', 'w') as json_file:
json_file.write(json.dumps(my_dict))
https://stackoverflow.com/questions/55132279
复制相似问题