【发布时间】:2020-08-27 06:13:07
【问题描述】:
我尝试使用以下 python 来解析示例文件(sample.txt)。但结果出乎意料。
样本:
# Summary Report #######################
System time | 2020-02-27 15:35:32 UTC (local TZ: UTC +0000)
# Instances ##################################################
Port Data Directory Nice OOM Socket
===== ========================== ==== === ======
0 0
# Configuration File #########################################
Config File | /etc/srv.cnf
[mysqld]
server_id = 1
port = 3016
tmpdir = /tmp
performance_schema_instrument = '%=on'
innodb_monitor_enable = 'module_adaptive_hash'
innodb_monitor_enable = 'module_buffer'
[client]
port = 3016
# management library ##################################
jemalloc is not enabled in mysql config for process with id 2425
# The End ####################################################
code.py
import json
import re
all_lines = open('sample.txt', 'r').readlines()
final_dict = {}
regex = r"^([a-zA-Z]+)(.)+="
config = 0 # not yet found config
for line in all_lines:
if '[mysqld]' in line:
final_dict['mysqld'] = {}
config = 1
continue
if '[client]' in line:
final_dict['client'] = {}
config = 2
continue
if config == 1 and re.search(regex, line):
try:
clean_line = line.strip() # get rid of empty space
k = clean_line.split('=')[0].rstrip() # get the key
v = clean_line.split('=')[1].lstrip()
final_dict['mysqld'][k] = v
except Exception as e:
print(clean_line, e)
if config == 2 and re.search(regex, line):
try:
clean_line = line.strip() # get rid of empty space
k = clean_line.split('=')[0].rstrip() # get the key
v = clean_line.split('=')[1].lstrip()
final_dict['client'][k] = v
except Exception as e:
print(clean_line, e)
print(final_dict)
print(json.dumps(final_dict, indent=4))
with open('my.json', 'w') as f:
json.dump(final_dict, f, sort_keys=True)
意想不到的结果:
{ “客户”: { “端口”:“3016” }, “mysqld”:{ "performance_schema_instrument": "'%", “server_id”:“1”, "innodb_monitor_enable": "'module_buffer'", “端口”:“3016”, “tmpdir”:“/tmp” } }
预期结果:
{
"client": {
"port": "3016"
},
"mysqld": {
"performance_schema_instrument": "'%=on'",
"server_id": "1",
"innodb_monitor_enable": "'module_buffer','module_adaptive_hash'",
"port": "3016",
"tmpdir": "/tmp"
}
}
是否有可能达到上述结果?
【问题讨论】:
-
你错过了什么?我发现的唯一区别是
performance_schema_instrument。是这个问题吗? -
看起来您只是想以更易于阅读的格式缩进 json 文件。您几乎拥有它 - 您将
indent=4包含在您的json.dumps命令中以显示自己,也将其包含在json.dump命令中以写入文件 (link) -
这看起来像一个配置文件。你看过 configparser 库吗?这个 libaray 为你解析配置文件。
-
解析后performance_schema_instrument的值应该是“'%=on'”,而不是“'%”。谢谢。