[英]python parse string to get contents between text
How can i collect the text (data) between a set of strings? 我如何收集一组字符串之间的文本(数据)? For example I have this code snippet below, which is a modified version of json, which I don't have the ability to change. 例如,我在下面有这个代码片段,它是json的修改版本,我无法更改。
However I want to collect the data between presets = {...}
但是我想在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,
},
},
}
So my resulting string would be whatever is between the two brackets {...}
following the word presets. 所以我的结果字符串将是单词presets之后的两个括号{...}
之间的任何内容。 In this case it would be: 在这种情况下,它将是:
location = "italy",
size = 10,
travelers = False,
My starting point so far... 我到目前为止的起点......
filepath = "C:/Users/jmartini/Projects/assets/tool_source.cfg"
with open(filepath, 'r') as file:
data = file.read().replace('\n', '').replace('\t', '')
print data
Use PyYaml to get the required data 使用PyYaml获取所需的数据
pip install PyYaml pip安装PyYaml
import yaml
def testjson():
with open('data.json') as datafile:
data = datafile.read().replace("\n", "").replace("=", ":")
print(yaml.load(data)["data"]["family"]["presets"])
I get this output with your data 我用你的数据得到这个输出
{'location': 'italy', 'size': 10, 'travelers': False}
You can use re
here. 你可以在这里使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.