python解析字符串以获取文本之间的内容

时间:2016-07-28 17:38:27

标签: python parsing

如何在一组字符串之间收集文本(数据)?例如,我在下面有这个代码片段,这是json的修改版本,我没有能力进行更改。

但是我想收集presets = {...}

之间的数据
{
    data = {
        friends = {
            max = 0 0,
            min = 0 0,
        },
        family = {
            cars = {
                van = "honda",
                car = "ford",
                bike = "trek",
            },
            presets = {
                location = "italy",
                size = 10,
                travelers = False,
            },
            version = 1,
        },
    },
}

因此,我的结果字符串将是单词presets之后的两个括号{...}之间的任何内容。在这种情况下,它将是:

location = "italy",
size = 10,
travelers = False,

到目前为止我的出发点......

filepath = "C:/Users/jmartini/Projects/assets/tool_source.cfg"

with open(filepath, 'r') as file:
    data = file.read().replace('\n', '').replace('\t', '')

    print data

2 个答案:

答案 0 :(得分:2)

使用PyYaml获取所需数据

  

pip install PyYaml

import yaml
def testjson():
    with open('data.json') as datafile:
        data = datafile.read().replace("\n", "").replace("=", ":")            
        print(yaml.load(data)["data"]["family"]["presets"])

我的数据输出

{'location': 'italy', 'size': 10, 'travelers': False}

答案 1 :(得分:1)

您可以在此处使用re

import re
filepath = r"C:/Users/jmartini/Projects/rogue_presetsManager/assets/tool_leveleditormodule_source.cfg"
f=open(filepath, "r")
data = f.read()
print re.findall(r"presets\s*=\s*\{\s*([^}]*?)\s*}", data)