- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
关于解析类似 JSON 的数据格式,我有两个有些相关的问题使用 pyparsing
。 目标是解析这些数据并将结果为 JSON。
1)第一类数据看起来像
mystr = """
DataName = {
fieldA = {
fieldB = 10
fieldC = "absf"
}
}
DataName = {
fieldA = {
fieldB = 11
fieldC = "bsf"
}
}
"""
我想知道按顺序设置语法的最佳方法是什么将 mystr
解析为看起来像的字典列表
expected_result = [{"DataName": {"fieldA": {"fieldB": 10, "fieldC": "absf"}}},
{"DataName": {"fieldA": {"fieldB": 11, "fieldC": "bsf"}}}]
我的第一次尝试如下
from pyparsing import *
LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas + '[]')
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()
value = (string | number)
jobject = Forward()
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef ^ jobject, delim=LineEnd())
jobject << Dict(field + EQUAL + LBRACE + Optional(members) + RBRACE)
members.parseString(mystr)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-70cbdee9640b> in <module>()
----> 1 members.parseString(mystr)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseString(self, instring, parseAll)
1204 instring = instring.expandtabs()
1205 try:
-> 1206 loc, tokens = self._parse( instring, 0 )
1207 if parseAll:
1208 loc = self.preParse( instring, loc )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2525 # pass False as last arg to _parse for first element, since we already
2526 # pre-parsed the string as part of our And pre-parsing
-> 2527 loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
2528 errorStop = False
2529 for e in self.exprs[1:]:
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2587 for e in self.exprs:
2588 try:
-> 2589 loc2 = e.tryParse( instring, loc )
2590 except ParseException as err:
2591 err.__traceback__ = None
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in tryParse(self, instring, loc)
1112 def tryParse( self, instring, loc ):
1113 try:
-> 1114 return self._parse( instring, loc, doActions=False )[0]
1115 except ParseFatalException:
1116 raise ParseException( instring, loc, self.errmsg, self)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2799 def parseImpl( self, instring, loc, doActions=True ):
2800 if self.expr is not None:
-> 2801 return self.expr._parse( instring, loc, doActions, callPreParse=False )
2802 else:
2803 raise ParseException("",loc,self.errmsg,self)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2799 def parseImpl( self, instring, loc, doActions=True ):
2800 if self.expr is not None:
-> 2801 return self.expr._parse( instring, loc, doActions, callPreParse=False )
2802 else:
2803 raise ParseException("",loc,self.errmsg,self)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2542 raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
2543 else:
-> 2544 loc, exprtokens = e._parse( instring, loc, doActions )
2545 if exprtokens or exprtokens.haskeys():
2546 resultlist += exprtokens
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
3004 def parseImpl( self, instring, loc, doActions=True ):
3005 try:
-> 3006 loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
3007 except (ParseException,IndexError):
3008 if self.defaultValue is not _optionalNotMatched:
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2525 # pass False as last arg to _parse for first element, since we already
2526 # pre-parsed the string as part of our And pre-parsing
-> 2527 loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
2528 errorStop = False
2529 for e in self.exprs[1:]:
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2587 for e in self.exprs:
2588 try:
-> 2589 loc2 = e.tryParse( instring, loc )
2590 except ParseException as err:
2591 err.__traceback__ = None
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in tryParse(self, instring, loc)
1112 def tryParse( self, instring, loc ):
1113 try:
-> 1114 return self._parse( instring, loc, doActions=False )[0]
1115 except ParseFatalException:
1116 raise ParseException( instring, loc, self.errmsg, self)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1070 if self.mayIndexError or loc >= len(instring):
1071 try:
-> 1072 loc,tokens = self.parseImpl( instring, preloc, doActions )
1073 except IndexError:
1074 raise ParseException( instring, len(instring), self.errmsg, self )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
2799 def parseImpl( self, instring, loc, doActions=True ):
2800 if self.expr is not None:
-> 2801 return self.expr._parse( instring, loc, doActions, callPreParse=False )
2802 else:
2803 raise ParseException("",loc,self.errmsg,self)
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
1076 loc,tokens = self.parseImpl( instring, preloc, doActions )
1077
-> 1078 tokens = self.postParse( instring, loc, tokens )
1079
1080 retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in postParse(self, instring, loc, tokenlist)
3247 tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
3248 else:
-> 3249 dictvalue = tok.copy() #ParseResults(i)
3250 del dictvalue[0]
3251 if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.haskeys()):
AttributeError: 'str' object has no attribute 'copy'
这不起作用,但我不清楚原因。 mystr
是一个 delimitedList
两个 jobject
(DataName
),其中每个 jobject
包含 1 个 jobject
(fieldA
) 由 1 个 members
组成,其中有两个 memberDefs
。我在这里缺少什么?
或者,我可以如下定义我的语法
value = Forward()
jobject = Forward()
value << (string | number | Group(jobject))
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members) + RBRACE)
res = members.parseString(mystr)
然后我可以遍历结果并生成字典,但是这感觉有点乱。
list_of_dicts = []
for pair in res:
list_of_dicts.append({pair[0]: pair[1].asDict()})
print(list_of_dicts)
[{'DataName': {'fieldA': {'fieldC': 'absf', 'fieldB': 10.0}}}, {'DataName': {'fieldA': {'fieldC': 'bsf', 'fieldB': 11.0}}}]
2) 数据格式还包括如下文本。
mystr2 = """
fieldA = {
someFieldA[] = {
}
someFieldB[] = {
"typeA", "typeB"
}
someFieldC[] = {
fieldData = {
data = 10
}
fieldData = {
data = 12
}
}
someFieldD = "bsf"
}
fieldA = {
}
"""
我想将其解析为字典列表,如下所示
expected_result2 = [{"fieldA": {"someFieldA": [],
"someFieldB": ["typeA", "typeB"],
"someFieldC":[{"fieldData": {"data": 10}},
{"fieldData": {"data": 10}}],
"someFieldD": "bsf"}},
{"fieldA": {}}]
我试图通过在语法中添加一个array
类型来解决这个问题
value = Forward()
jobject = Forward()
arrayElements = delimitedList(string)
array = Group(LBRACE + Optional(arrayElements, []) + RBRACE)
value << (string | number | Group(jobject) | array)
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members) + RBRACE)
res2 = members.parseString(mystr2)
print(res2)
[['fieldA', [['someFieldA[]', []], ['someFieldB', ['typeA', 'typeB']], ['someFieldC[]', [['fieldData', [['data', 10.0]]], ['fieldData', [['data', 12.0]]]]], ['someFieldD', 'bsf']]], ['fieldA', []]]
这会返回一个 parseResult 但是我不确定如何进行转换变成类似 expected_result2
的东西。另外,上面的语法中也没有区分form的元素
Data = {
}
和
Data[] = {
}
应该分别映射到 {"Data": {}}
和 {"Data": []}
。
上面的mystr2
有错别字,someFieldB[] = {
被错误地写成了someFieldB = {
解释 []
重要性的语法如下所示。
LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas)
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()
scalar_value = (string | number)
value_list = Forward()
jobject = Forward()
memberDef1 = Group(field + EQUAL + scalar_value)
memberDef2 = Group(field + EQUAL + jobject)
memberDef3 = Group(field + "[]" + EQUAL + LBRACE + value_list + RBRACE)
memberDef = memberDef1 | memberDef2 | memberDef3
value_list << (delimitedList(string, ",") | ZeroOrMore(memberDef2))
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members, '{}') + RBRACE)
res = members.parseString(mystr2)
这似乎可以正确解析,但我仍然不清楚如何将 res
转换为字典列表?
下面包含一个说明语法的实际示例
HistoricalDataRequest = {
securities[] = {
"SPY US Equity", "TLT US Equity"
}
fields[] = {
"PX_LAST"
}
startDate = "20150629"
endDate = "20150630"
overrides[] = {
}
}
HistoricalDataResponse = {
securityData = {
security = "SPY US Equity"
eidData[] = {
}
sequenceNumber = 0
fieldExceptions[] = {
}
fieldData[] = {
fieldData = {
date = 2015-06-29
PX_LAST = 205.420000
}
fieldData = {
date = 2015-06-30
PX_LAST = 205.850000
}
}
}
}
HistoricalDataResponse = {
securityData = {
security = "TLT US Equity"
eidData[] = {
}
sequenceNumber = 1
fieldExceptions[] = {
}
fieldData[] = {
fieldData = {
date = 2015-06-29
PX_LAST = 118.280000
}
fieldData = {
date = 2015-06-30
PX_LAST = 117.460000
}
}
}
}
最佳答案
好吧,经过一些花招和恶作剧,我想我已经发明了一个解析器,可以从这种格式中为您提供支持 JSON 的字典。
LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas, alphas+'_')
# was field = Word(alphas)
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()
date_expr = Regex(r'\d\d\d\d-\d\d-\d\d')
scalar_value = (string | date_expr | number)
# was scalar_value = (string | number)
list_marker = Suppress("[]")
value_list = Forward()
jobject = Forward()
memberDef1 = Group(field + EQUAL + scalar_value)
memberDef2 = Group(field + EQUAL + jobject)
memberDef3 = Group(field + list_marker + EQUAL + LBRACE + value_list + RBRACE)
memberDef = memberDef1 | memberDef2 | memberDef3
value_list <<= (delimitedList(scalar_value, ",") | ZeroOrMore(Group(Dict(memberDef2))))
value_list.setParseAction(lambda t: [ParseResults(t[:])])
members = OneOrMore(memberDef)
jobject <<= Dict(LBRACE + ZeroOrMore(memberDef) + RBRACE)
# force empty jobject to be a dict
jobject.setParseAction(lambda t: t or {})
parser = members
parser = OneOrMore(Group(Dict(memberDef)))
tests = [mystr, mystr2]
import pprint
import json
for test in tests:
print(test)
res = parser.parseString(test)
for res_dict in res:
pprint.pprint(res_dict.asDict())
# or convert to JSON using:
# print(json.dumps(res_dict.asDict(), indent=2))
print('')
打印(为 someFieldE
添加空 jobject
并为 someFieldF
添加空列表):
{'DataName': {'fieldA': {'fieldB': 10, 'fieldC': 'absf'}}}
{'DataName': {'fieldA': {'fieldB': 11, 'fieldC': 'bsf'}}}
{'fieldA': {'someFieldA': [],
'someFieldB': ['typeA', 'typeB'],
'someFieldC': [{'a': {'data': 10}}, {'a': {'data': 12}}],
'someFieldD': 'bsf',
'someFieldE': {},
'someFieldF': []}}
我使用 Group
围绕 Dict
处理多个字典键,这样重复的键将被隔离到单独的 ParseResults
。 value_list
上的解析操作在那里,以便空列表在列表中返回空的 ParseResults
。我不得不强制将空的 jobject
变成字典,因为将它们保留为空的 ParseResults
将没有任何键,因此不会从 asDict 返回字典()
。
(编辑:为了适应您发布的示例,我必须添加“_”作为有效的字段名称字符,并且还为类似日期的字段值定义了一个新的 date_expr
类型。)
关于python - 使用 pyparsing 解析类似 JSON 的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44144055/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!