如何在一组字符串之间收集文本(数据)?例如,我在下面有这个代码片段,这是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
答案 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)