本文整理汇总了Python中pyparsing.nestedExpr方法的典型用法代码示例。如果您正苦于以下问题:Python pyparsing.nestedExpr方法的具体用法?Python pyparsing.nestedExpr怎么用?Python pyparsing.nestedExpr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing
的用法示例。
在下文中一共展示了pyparsing.nestedExpr方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: expression
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def expression(self):
expression = pyparsing.Forward()
# (1 + (2 + 3))
nested_expression = pyparsing.nestedExpr(
"(", ")", expression).setParseAction(self._combine_lists)
# FOO(2 , 3)
function_call = (
_TOKEN().setResultsName("function")
+ _OPEN_PARENTHESIS()
+ pyparsing.delimitedList(
pyparsing.Combine(expression, adjacent=False, joinString=" "),
delim=",").setResultsName("func_args")
+ _CLOSE_PARENTHESIS()
)
expression << pyparsing.OneOrMore(
function_call.setParseAction(self._is_known_function)
| pyparsing.Group(nested_expression)
| _TOKEN()
| _NOT_TOKEN()
)
return pyparsing.Combine(expression, adjacent=False, joinString=" ")
示例2: OperationsSchema
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def OperationsSchema(v):
if isinstance(v, six.text_type):
try:
v = pyparsing.OneOrMore(
pyparsing.nestedExpr()).parseString(v).asList()[0]
except pyparsing.ParseException as e:
api.abort(400, {"cause": "Invalid operations",
"reason": "Fail to parse the operations string",
"detail": six.text_type(e)})
return voluptuous.Schema(voluptuous.Any(*OperationsSchemaBase),
required=True)(v)
示例3: parse_parentheses
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def parse_parentheses(line):
try:
return nestedExpr('(', ')').parseString(line).asList()
except ParseException:
print "Exception on line:", line
示例4: sanitize
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def sanitize(type_repr: str):
type_repr = re.sub(r'<class \'(.*)\'>', r'\1', type_repr)
type_repr = type_repr.replace('typing.', '')
type_repr = type_repr.replace('torch_sparse.tensor.', '')
type_repr = type_repr.replace('Adj', 'Union[Tensor, SparseTensor]')
# Replace `Union[..., NoneType]` by `Optional[...]`.
sexp = pp.nestedExpr(opener='[', closer=']')
tree = sexp.parseString(f'[{type_repr.replace(",", " ")}]').asList()[0]
def union_to_optional_(tree):
for i in range(len(tree)):
e, n = tree[i], tree[i + 1] if i + 1 < len(tree) else []
if e == 'Union' and n[-1] == 'NoneType':
tree[i] = 'Optional'
tree[i + 1] = tree[i + 1][:-1]
elif e == 'Union' and 'NoneType' in n:
idx = n.index('NoneType')
n[idx] = [n[idx - 1]]
n[idx - 1] = 'Optional'
elif isinstance(e, list):
tree[i] = union_to_optional_(e)
return tree
tree = union_to_optional_(tree)
type_repr = re.sub(r'\'|\"', '', str(tree)[1:-1]).replace(', [', '[')
return type_repr
示例5: gen_set
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def gen_set(pattern_single):
pattern_set = pp.nestedExpr(
opener='(', closer=')',
content=pp.delimitedList(pattern_single, delim=delim)) \
.setParseAction(patternSetOp)
pattern_ = pattern_single | pattern_set
return pattern_
# define a function that can add *+! to the end
示例6: todict
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def todict(cls, parseresult, mode='parens', ns={}):
"""
Helper function to return dictionary given the parse results
from a pyparsing.nestedExpr object (containing keywords).
The ns is a dynamic namespace (typically the IPython Notebook
namespace) used to update the class-level namespace.
"""
grouped, kwargs = [], {}
tokens = cls.collect_tokens(parseresult, mode)
# Group tokens without '=' and append to last token containing '='
for group in groupby(tokens, lambda el: '=' in el):
(val, items) = group
if val is True:
grouped += list(items)
if val is False:
elements =list(items)
# Assume anything before ) or } can be joined with commas
# (e.g tuples with spaces in them)
joiner=',' if any(((')' in el) or ('}' in el))
for el in elements) else ''
grouped[-1] += joiner + joiner.join(elements)
for keyword in grouped:
# Tuple ('a', 3) becomes (,'a',3) and '(,' is never valid
# Same for some of the other joining errors corrected here
for (fst,snd) in [('(,', '('), ('{,', '{'), ('=,','='),
(',:',':'), (':,', ':'), (',,', ','),
(',.', '.')]:
keyword = keyword.replace(fst, snd)
try:
kwargs.update(eval('dict(%s)' % keyword,
dict(cls.namespace, **ns)))
except:
if cls.abort_on_eval_failure:
raise SyntaxError("Could not evaluate keyword: %r"
% keyword)
msg = "Ignoring keyword pair that fails to evaluate: '%s'"
parsewarning.warning(msg % keyword)
return kwargs
示例7: find_enclosed_elem
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def find_enclosed_elem(annotated_sent, start_symbol, end_symbol):
"""
Extract elements enclosed by some denotation.
"""
sexp = nestedExpr(start_symbol,
end_symbol,
ignoreExpr = None).parseString("{}{}{}".format(start_symbol,
annotated_sent,
end_symbol)).asList()[0]
exps = [get_raw_sent(" ".join(ls))
for ls in sexp
if isinstance(ls, list)]
# Make sure there's a single predicate head
return exps