本文整理汇总了Python中pyparsing.Literal.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Literal.setParseAction方法的具体用法?Python Literal.setParseAction怎么用?Python Literal.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Literal
的用法示例。
在下文中一共展示了Literal.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def __init__(self, path, text, state=None):
self.path = path
self.base_path = os.path.dirname(path)
self.text = text
self.state = state
opcode_name = Word(alphanums + '_')
value = Regex(r'.*?(?=\s*(([a-zA-Z0-9_]+=)|//|<[a-z]|$))', re.MULTILINE)
opcode = locatedExpr(opcode_name) + Literal('=').suppress() + value
opcode.setParseAction(self.handle_opcode)
section_name = Literal('<').suppress() + Word(alphas) + Literal('>').suppress()
section = section_name
section.setParseAction(self.handle_section)
include = Literal('#include').suppress() + locatedExpr(QuotedString('"'))
include.setParseAction(self.handle_include)
statement = (section
^ opcode
^ include)
self.sfz_file = ZeroOrMore(statement) + stringEnd
comment = Literal('//') + restOfLine
self.sfz_file.ignore(comment)
示例2: _define_valued_characters_section
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def _define_valued_characters_section(self, heading, characters,
parse_action, character_type):
"""Returns a parser object for a section specifying characters
and their valued features.
:param heading: section heading
:type heading: `str`
:param characters: valid characters
:type characters: `list` of `str`
:param parse_action: parse action for a character
:type parse_action: `function`
:param character_type: type of characters being described
:type character_type: `str`
"""
heading = Literal('[{}]'.format(heading))
character = Word(''.join(characters), exact=1).setResultsName(
'character')
character.setParseAction(self._handle_character)
feature = Word(alphas).setResultsName('feature')
feature.setParseAction(parse_action)
value = Literal('+') ^ Literal('-') ^ Literal('\N{MINUS SIGN}')
value.setParseAction(self._handle_feature_value)
feature_value = Group(value + feature)
feature_values = Group(delimitedList(feature_value))
character_definition = Dict(Group(character + Suppress(':') +
feature_values))
character_definitions = Group(OneOrMore(character_definition)).setResultsName(character_type)
section = Suppress(heading) + character_definitions
return section
示例3: _define_context_component
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def _define_context_component (self, cluster, base_feature_set):
placeholder = Literal(SOURCE_PLACEHOLDER)
placeholder.setParseAction(self._handle_placeholder)
context_component = Group(ZeroOrMore(cluster ^ base_feature_set) + \
placeholder + ZeroOrMore(cluster ^ base_feature_set)).setResultsName('context_component')
context_component.setParseAction(self._handle_context_component)
return context_component
示例4: grammar
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def grammar():
parenthesis = Forward()
parenthesis <<= "(" + ZeroOrMore(CharsNotIn("()") | parenthesis) + ")"
field_def = OneOrMore(Word(alphanums + "_\"'`:-") | parenthesis)
field_def.setParseAction(field_act)
tablename_def = ( Word(alphas + "`_") | QuotedString("\"") )
field_list_def = field_def + ZeroOrMore(Suppress(",") + field_def)
field_list_def.setParseAction(field_list_act)
create_table_def = Literal("CREATE") + "TABLE" + tablename_def.setResultsName("tableName") + "(" + field_list_def.setResultsName("fields") + ")" + ";"
create_table_def.setParseAction(create_table_act)
add_fkey_def = Literal("ALTER") + "TABLE" + "ONLY" + tablename_def.setResultsName("tableName") + "ADD" + "CONSTRAINT" + Word(alphanums + "_") + "FOREIGN" + "KEY" + "(" + Word(alphanums + "_").setResultsName("keyName") + ")" + "REFERENCES" + Word(alphanums + "_").setResultsName("fkTable") + "(" + Word(alphanums + "_").setResultsName("fkCol") + ")" + ";"
add_fkey_def.setParseAction(add_fkey_act)
other_statement_def = OneOrMore(CharsNotIn(";")) + ";"
other_statement_def.setParseAction(other_statement_act)
comment_def = "--" + ZeroOrMore(CharsNotIn("\n"))
comment_def.setParseAction(other_statement_act)
return OneOrMore(comment_def | create_table_def | add_fkey_def | other_statement_def)
示例5: _logical_parser
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def _logical_parser(expression):
"""
Return a new parser parsing logical expressions.
This parser recognizes the following grammar, with precedence:
<logical> ::= expression | '~' <logical> | <logical> '&' <logical>
| <logical> '|' <logical> | <logical> '->' <logical>
| <logical> '<->' <logical>
.. note:: The parser uses :mod:`pytlq.ast` module's classes to build ASTs.
.. credit:: Adapted from Simon Busard's parser parsing logical expressions
on atomics.
"""
parser = Forward()
not_strict = Literal('~') + expression
not_strict.setParseAction(lambda tokens: Not(tokens[1]))
not_ = (not_strict | expression)
and_ = not_ + ZeroOrMore(Literal('&') + not_)
and_.setParseAction(lambda tokens: _left(And, tokens))
or_ = and_ + ZeroOrMore(Literal('|') + and_)
or_.setParseAction(lambda tokens: _left(Or, tokens))
imply = ZeroOrMore(or_ + Literal('->')) + or_
imply.setParseAction(lambda tokens: _right(Imply, tokens))
iff = imply + ZeroOrMore(Literal('<->') + imply)
iff.setParseAction(lambda tokens: _left(Iff, tokens))
parser <<= iff
return parser
示例6: parser
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
lbrack, rbrack, lbrace, rbrace, lparen, rparen = map(Literal, "[]{}()")
reMacro = Combine("\\" + oneOf(list("dws")))
escapedChar = ~ reMacro + Combine("\\" + oneOf(list(printables)))
reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"
reRange = Combine(lbrack + SkipTo(rbrack, ignore=escapedChar) + rbrack)
reLiteral = (escapedChar | oneOf(list(reLiteralChar)))
reDot = Literal(".")
repetition = (
(lbrace + Word(nums).setResultsName("count") + rbrace) |
(lbrace + Word(nums).setResultsName("minCount") + "," + Word(nums).setResultsName("maxCount") + rbrace) |
oneOf(list("*+?"))
)
reRange.setParseAction(handle_range)
reLiteral.setParseAction(handle_literal)
reMacro.setParseAction(handle_macro)
reDot.setParseAction(handle_dot)
reTerm = (reLiteral | reRange | reMacro | reDot)
reExpr = operatorPrecedence(reTerm, [
(repetition, 1, opAssoc.LEFT, handle_repetition),
(None, 2, opAssoc.LEFT, handle_sequence),
(Suppress('|'), 2, opAssoc.LEFT, handle_alternative),
])
_parser = reExpr
return _parser
示例7: parseArctl
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def parseArctl(spec):
"""Parse the spec and return its AST."""
global __arctl
if __arctl is None:
true = Literal("True")
true.setParseAction(lambda tokens: TrueExp())
false = Literal("False")
false.setParseAction(lambda tokens: FalseExp())
atom = "'" + SkipTo("'") + "'"
atom.setParseAction(lambda tokens: Atom(tokens[1]))
action = _logicals_(atom)
__arctl = Forward()
proposition = true | false | atom
notproposition = "~" + proposition
notproposition.setParseAction(lambda tokens: Not(tokens[1]))
formula = proposition | notproposition | Suppress("(") + __arctl + Suppress(")")
temporal = Forward()
e = Literal("E") + "<" + action + ">"
a = Literal("A") + "<" + action + ">"
eax = e + "X" + temporal
eax.setParseAction(lambda tokens: EaX(tokens[2], tokens[5]))
aax = a + "X" + temporal
aax.setParseAction(lambda tokens: AaX(tokens[2], tokens[5]))
eaf = e + "F" + temporal
eaf.setParseAction(lambda tokens: EaF(tokens[2], tokens[5]))
aaf = a + "F" + temporal
aaf.setParseAction(lambda tokens: AaF(tokens[2], tokens[5]))
eag = e + "G" + temporal
eag.setParseAction(lambda tokens: EaG(tokens[2], tokens[5]))
aag = a + "G" + temporal
aag.setParseAction(lambda tokens: AaG(tokens[2], tokens[5]))
eau = e + "[" + __arctl + "U" + __arctl + "]"
eau.setParseAction(lambda tokens: EaU(tokens[2], tokens[5], tokens[7]))
aau = a + "[" + __arctl + "U" + __arctl + "]"
aau.setParseAction(lambda tokens: AaU(tokens[2], tokens[5], tokens[7]))
eaw = e + "[" + __arctl + "W" + __arctl + "]"
eaw.setParseAction(lambda tokens: EaW(tokens[2], tokens[5], tokens[7]))
aaw = a + "[" + __arctl + "W" + __arctl + "]"
aaw.setParseAction(lambda tokens: AaW(tokens[2], tokens[5], tokens[7]))
temporal <<= formula | eax | aax | eaf | aaf | eag | aag | eau | aau | eaw | aaw
logical = _logicals_(temporal)
__arctl <<= logical
return __arctl.parseString(spec, parseAll=True)
示例8: __init__
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def __init__(self):
self.variables = dict()
#_base_var = Literal("$") + (("{" + Word(alphanums + "_-").setResultsName("var_name", listAllMatches=True) + Optional("[" + Word(nums + "*@") + "]") + "}")
#| Word(alphanums))
_simple_var = Literal("$") + Word(alphanums + "_-").setResultsName("varname")
_brace_substitute_part = Optional("/" + (Word(alphanums + "_-").setResultsName("orig"))
+ Optional("/" + Word(alphanums + "_-!?/\\").setResultsName("new")))
_array_access = "[" + Word(nums + "@*").setResultsName("position") + "]"
_brace_var = Literal("${") + Word(alphanums + "_-").setResultsName("text") + _brace_substitute_part + Optional(_array_access) + "}"
_brace_var.setParseAction(lambda x: x if not x.new else re.sub(x.orig, x.new, x.text))
_base_var = _simple_var | _brace_var
self.var = ('"' + _base_var + '"') | _base_var
self.var("variable")
示例9: getkw_bnf
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def getkw_bnf(self):
sect_begin = Literal("{").suppress()
sect_end = Literal("}").suppress()
array_begin = Literal("[").suppress()
array_end = Literal("]").suppress()
tag_begin = Literal("<").suppress()
tag_end = Literal(">").suppress()
eql = Literal("=").suppress()
dmark = Literal('$').suppress()
end_data=Literal('$end').suppress()
prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'
ival=Regex('[-]?\d+')
dval=Regex('-?\d+\.\d*([eE]?[+-]?\d+)?')
lval=Regex('([Yy]es|[Nn]o|[Tt]rue|[Ff]alse|[Oo]n|[Oo]ff)')
# Helper definitions
kstr= quotedString.setParseAction(removeQuotes) ^ \
dval ^ ival ^ lval ^ Word(prtable)
name = Word(alphas+"_",alphanums+"_")
vec=array_begin+delimitedList(dval ^ ival ^ lval ^ Word(prtable) ^ \
Literal("\n").suppress() ^ \
quotedString.setParseAction(removeQuotes))+array_end
sect=name+sect_begin
tag_sect=name+Group(tag_begin+name+tag_end)+sect_begin
# Grammar
keyword = name + eql + kstr
vector = name + eql + vec
data=Combine(dmark+name)+SkipTo(end_data)+end_data
section=Forward()
sect_def=(sect | tag_sect ) #| vec_sect)
input=section | data | vector | keyword
section << sect_def+ZeroOrMore(input) + sect_end
# Parsing actions
ival.setParseAction(self.conv_ival)
dval.setParseAction(self.conv_dval)
lval.setParseAction(self.conv_lval)
keyword.setParseAction(self.store_key)
vector.setParseAction(self.store_vector)
data.setParseAction(self.store_data)
sect.setParseAction(self.add_sect)
tag_sect.setParseAction(self.add_sect)
sect_end.setParseAction(self.pop_sect)
bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
bnf.ignore(pythonStyleComment)
return bnf
示例10: parser
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
lbrack = Literal("[")
rbrack = Literal("]")
lbrace = Literal("{")
rbrace = Literal("}")
lparen = Literal("(")
rparen = Literal(")")
reMacro = Suppress("\\") + oneOf(list("dwsZ"))
escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
reLiteralChar = "".join(c for c in string.printable if c not in r"\[]{}().*?+|")
reRange = Combine(lbrack.suppress() + SkipTo(rbrack,ignore=escapedChar) + rbrack.suppress())
reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
reDot = Literal(".")
repetition = (
( lbrace + Word(nums).setResultsName("count") + rbrace ) |
( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
oneOf(list("*+?"))
)
reExpr = Forward()
reGroup = (lparen.suppress() +
Optional(Literal("?").suppress() + oneOf(list(":P"))).setResultsName("option") +
reExpr.setResultsName("expr") +
rparen.suppress())
reTerm = ( reLiteral | reRange | reMacro | reDot | reGroup )
reExpr << operatorPrecedence( reTerm,
[
(repetition, 1, opAssoc.LEFT, create(Repetition)),
(None, 2, opAssoc.LEFT, create(Sequence)),
(Suppress('|'), 2, opAssoc.LEFT, create(Alternation)),
]
)
reGroup.setParseAction(create(Group))
reRange.setParseAction(create(Range))
reLiteral.setParseAction(create(Character))
reMacro.setParseAction(create(Macro))
reDot.setParseAction(create(Dot))
_parser = reExpr
return _parser
示例11: __init__
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def __init__(self):
left_bracket = Literal("{").suppress()
right_bracket = Literal("}").suppress()
semicolon = Literal(";").suppress()
space = White().suppress()
key = Word(alphanums + "+.-_/")
value = ZeroOrMore(
CharsNotIn('{};#"\'') | space |
QuotedString("'", escChar='\\', multiline=True) |
QuotedString('"', escChar='\\', multiline=True))
# modifier for location uri [ = | ~ | ~* | ^~ ]
modifier = Literal("=") | Literal("~*") | Literal("~") | Literal("^~")
comment = Literal('#').suppress() + Optional(restOfLine)
# rules
assignment = Group(
(key | value) + value + semicolon +
Optional(space + comment))
block = Forward()
block << Group(
Group(key + Optional(space + modifier) + Optional(space) +
Optional(value) + Optional(space + value)) +
left_bracket +
Group(ZeroOrMore(assignment | block | comment.suppress())) +
right_bracket)
def comment_handler(t):
result = []
if "promo" in t[0]:
result.append("promo")
if "author: " in t[0]:
try:
email = t[0].split("author: ")[1].strip()
result.append(email)
except Exception:
result.append(t[0])
return result
comment.setParseAction(comment_handler)
self.script = OneOrMore(assignment | block | comment.suppress())
示例12: getkw_bnf
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def getkw_bnf(self):
sect_begin = Literal("{").suppress()
sect_end = Literal("}").suppress()
array_begin = Literal("[").suppress()
array_end = Literal("]").suppress()
arg_begin = Literal("(").suppress()
arg_end = Literal(")").suppress()
eql = Literal("=").suppress()
dmark = Literal('$').suppress()
end_data=Literal('$end').suppress()
prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'
# Helper definitions
kstr=Word(prtable) ^ quotedString.setParseAction(removeQuotes)
name = Word(alphas+"_",alphanums+"_")
vec=array_begin+delimitedList(Word(prtable) ^ \
Literal("\n").suppress() ^ \
quotedString.setParseAction(removeQuotes))+array_end
sect=name+sect_begin
key_sect=name+Group(arg_begin+kstr+arg_end)+sect_begin
vec_sect=name+Group(arg_begin+vec+ arg_end)+sect_begin
# Grammar
keyword = name + eql + kstr
vector = name + eql + vec
data=Combine(dmark+name)+SkipTo(end_data)+end_data
section=Forward()
sect_def=(sect | key_sect | vec_sect)
input=section | data | vector | keyword
section << sect_def+ZeroOrMore(input) + sect_end
# Parsing actions
keyword.setParseAction(self.store_key)
vector.setParseAction(self.store_vector)
data.setParseAction(self.store_data)
sect.setParseAction(self.add_sect)
key_sect.setParseAction(self.add_sect)
vec_sect.setParseAction(self.add_vecsect)
sect_end.setParseAction(self.pop_sect)
bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
bnf.ignore(pythonStyleComment)
return bnf
示例13: _getPattern
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def _getPattern(self):
arith_expr = Forward()
comp_expr = Forward()
logic_expr = Forward()
LPAR, RPAR, SEMI = map(Suppress, "();")
identifier = Word(alphas+"_", alphanums+"_")
multop = oneOf('* /')
plusop = oneOf('+ -')
expop = Literal( "^" )
compop = oneOf('> < >= <= != ==')
andop = Literal("AND")
orop = Literal("OR")
current_value = Literal( "." )
assign = Literal( "=" )
# notop = Literal('NOT')
function = oneOf(' '.join(self.FUNCTIONS))
function_call = Group(function.setResultsName('fn') + LPAR + Optional(delimitedList(arith_expr)) + RPAR)
aggregate_column = QuotedString(quoteChar='{', endQuoteChar='}')
single_column = QuotedString(quoteChar='[', endQuoteChar=']')
integer = Regex(r"-?\d+")
real = Regex(r"-?\d+\.\d*")
# quotedString enables strings without quotes to pass
operand = \
function_call.setParseAction(self.__evalFunction) | \
aggregate_column.setParseAction(self.__evalAggregateColumn) | \
single_column.setParseAction(self.__evalSingleColumn) | \
((real | integer).setParseAction(self.__evalConstant)) | \
quotedString.setParseAction(self.__evalString).addParseAction(removeQuotes) | \
current_value.setParseAction(self.__evalCurrentValue) | \
identifier.setParseAction(self.__evalString)
arith_expr << operatorPrecedence(operand,
[
(expop, 2, opAssoc.LEFT, self.__expOp),
(multop, 2, opAssoc.LEFT, self.__multOp),
(plusop, 2, opAssoc.LEFT, self.__addOp),
])
# comp_expr = Group(arith_expr + compop + arith_expr)
comp_expr << operatorPrecedence(arith_expr,
[
(compop, 2, opAssoc.LEFT, self.__evalComparisonOp),
])
logic_expr << operatorPrecedence(comp_expr,
[
(andop, 2, opAssoc.LEFT, self.__evalLogicOp),
(orop, 2, opAssoc.LEFT, self.__evalLogicOp)
])
pattern = logic_expr + StringEnd()
return pattern
示例14: define_number
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def define_number(self):
"""
Return the syntax definition for a number in Arabic Numerals.
Override this method to support numeral systems other than Arabic
Numerals (0-9).
Do not override this method just to change the character used to
separate thousands and decimals: Use :attr:`T_THOUSANDS_SEPARATOR`
and :attr:`T_DECIMAL_SEPARATOR`, respectively.
"""
# Defining the basic tokens:
to_dot = lambda t: "."
to_plus = lambda t: "+"
to_minus = lambda t: "-"
positive_sign = Literal(self._grammar.get_token("positive_sign"))
positive_sign.setParseAction(to_plus)
negative_sign = Literal(self._grammar.get_token("negative_sign"))
negative_sign.setParseAction(to_minus)
decimal_sep = Literal(self._grammar.get_token("decimal_separator"))
decimal_sep.setParseAction(to_dot)
thousands_sep = Suppress(self._grammar.get_token("thousands_separator"))
digits = Word(nums)
# Building the integers and decimals:
sign = positive_sign | negative_sign
thousands = Word(nums, max=3) + \
OneOrMore(thousands_sep + Word(nums, exact=3))
integers = thousands | digits
decimals = decimal_sep + digits
number = Combine(Optional(sign) + integers + Optional(decimals))
number.setParseAction(self.make_number)
number.setName("number")
return number
示例15: _get_bus_array_construct
# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import setParseAction [as 别名]
def _get_bus_array_construct(self):
""" Returns a construct for an array of bus data.
"""
bus_no = integer.setResultsName("bus_no")
v_base = real.setResultsName("v_base") # kV
v_magnitude = Optional(real).setResultsName("v_magnitude")
v_angle = Optional(real).setResultsName("v_angle") # radians
area = Optional(integer).setResultsName("area") # not used yet
region = Optional(integer).setResultsName("region") # not used yet
bus_data = bus_no + v_base + v_magnitude + v_angle + \
area + region + scolon
bus_data.setParseAction(self.push_bus)
bus_array = Literal("Bus.con") + "=" + "[" + "..." + \
ZeroOrMore(bus_data + Optional("]" + scolon))
# Sort buses according to their name (bus_no)
bus_array.setParseAction(self.sort_buses)
return bus_array