当前位置: 首页 > 知识库问答 >
问题:

如何用Python解析文本文件的特定块并导出json格式

解明辉
2023-03-14

我尝试使用下面的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 ####################################################
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)

{
    "client": {
        "port": "3016"
    }, 
    "mysqld": {
        "performance_schema_instrument": "'%=on'", 
        "server_id": "1", 
        "innodb_monitor_enable": "'module_buffer','module_adaptive_hash'", 
        "port": "3016", 
        "tmpdir": "/tmp"
    }
}

共有1个答案

关飞翔
2023-03-14

configparser用于处理Python中的配置文件设置。

import configparser, re, json

regex_string         = '# Configuration File #.*?\n(\[.*?)# management library #'
configuration_string = re.findall(regex_string,open('temp').read(),re.DOTALL)[0]

c = configparser.RawConfigParser(strict=False)
c.read_string(configuration_string)

settings = {k:dict(v) for k,v in c.items() if k!='DEFAULT'}
json.dump(settings,open('temp.json','w'),sort_keys=True,indent=4)
 类似资料:
  • 问题内容: 我正在寻找一种将复杂文本文件解析为pandas DataFrame的简单方法。下面是一个示例文件,我希望解析后的结果是什么样,以及我当前的方法。 有什么方法可以使其更简洁/更快/更pythonic /更易读? 我也把这个问题放在了Code Review上 。 我最终写了一篇博客文章向初学者解释。 这是一个示例文件: 这是我希望解析后的结果看起来像什么: 这是我目前解析的方式: 问题答案

  • 问题内容: 到目前为止,我的目标是在Rust中解析此JSON数据: 并且是 我下一步应该解析什么?我的主要目标是获取这样的JSON数据,并从其中解析密钥(例如Age)。 问题答案: Serde是首选的JSON序列化提供程序。您可以通过多种方式从文件中读取JSON文本。将其作为字符串使用后,请使用: Cargo.toml: 您甚至可以使用类似的方法直接从已打开的读取。 Serde可以用于JSON以外

  • 我有一个非常简单的产品评论JSON,比如: 我想用GSON把它读到我的Java应用程序中。我构建了一个类来保存每次复习的结果: 使用这段代码,我只能检索JSON中的第一个评论,所以我的问题是:如何遍历所有阅读器并获得下一个评论?我不需要将评论存储在列表中,只需要访问对象一次。任何帮助都大于欢迎。

  • 本文向大家介绍python处理文本文件并生成指定格式的文件,包括了python处理文本文件并生成指定格式的文件的使用技巧和注意事项,需要的朋友参考一下

  • 问题内容: 我是iOS开发人员中的新手,并且尝试解析本地Json文件,例如 这是我的代码: 我在此站点上找到了一个示例,但出现以下错误 -JSONValue失败。错误是:对象键后不期望令牌“值分隔符”。 问题答案: JSON具有严格的键/值表示法,用于R4和响应的键/值对不正确。试试这个: 如果您从文件中读取字符串,则不需要所有的斜杠。 文件将如下所示: {“ quizz”:[{“ id”:“ 1

  • 问题内容: 我有一个看起来像这样的日志文件(简化) Logline样本 我想提取 数据中 包含的json 并创建两个字段,一个用于名字,一个用于姓氏。但是,我得到的输出是这样的: 如你看到的 那不是我所需要的,我需要在kibana中为firstname和lastname创建字段,但是logstash不会使用json过滤器提取字段。 LogStash配置 非常感谢任何帮助,我敢肯定我错过了一些简单的