在Python中解析自定义文本文件

2024-06-16 10:59:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本需要解析,这是一个简洁的文本形式。在

apple {
    type=fruit
    varieties {
        color=red
        origin=usa
    }
}

输出应如下所示

^{pr2}$

到目前为止,我唯一想到的是python中一种宽度优先的方法。但我想不出怎么把所有的孩子都关在里面。在

progInput = """apple {
    type=fruit
    varieties {
        color=red
        origin=usa
    }
}
"""
progInputSplitToLines = progInput.split('\n')
childrenList = []
root = ""

def hasChildren():
    if "{" in progInputSplitToLines[0]:
        global root
        root = progInputSplitToLines[0].split(" ")[0]
    for e in progInputSplitToLines[1:]:
        if "=" in e:
            childrenList.append({e.split("=")[0].replace("    ", ""),e.split("=")[1].replace("    ", "")})
hasChildren()

PS:我研究了Python中的树结构,发现了anytree(https://anytree.readthedocs.io/en/latest/),您认为这对我的情况有帮助吗?在

你能帮帮我吗?我不太擅长分析文本。提前谢谢你。:)


Tags: in文本appletyperedrootorigincolor
1条回答
网友
1楼 · 发布于 2024-06-16 10:59:32

由于您的文件是HOCON格式的,您可以尝试使用^{}HOCON解析器模块来解决您的问题。在

安装:运行pip install pyhocon,或者下载github repo并使用python setup.py install执行手动安装。在

基本用法:

from pyhocon import ConfigFactory

conf = ConfigFactory.parse_file('text.conf')

print(conf)

它给出了以下嵌套结构:

^{pr2}$

^{}只是一个^{},如source code所示。在

更新:

要获得所需的输出,可以使用自己的递归函数来收集所有路径:

from pyhocon import ConfigFactory
from pyhocon.config_tree import ConfigTree

def config_paths(config):
    for k, v in config.items():
        if isinstance(v, ConfigTree):
            for k1, v1 in config_paths(v):
                yield (k,) + k1, v1
        else:
            yield (k,), v

config = ConfigFactory.parse_file('text.conf')
for k, v in config_paths(config):
    print('%s=%s' % ('.'.join(k), v))

哪些输出:

apple.type=fruit
apple.varieties.color=red
apple.varieties.origin=usa

相关问题 更多 >