本文整理汇总了Python中pyparsing.Forward类的典型用法代码示例。如果您正苦于以下问题:Python Forward类的具体用法?Python Forward怎么用?Python Forward使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Forward类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: parse_sexp
def parse_sexp(data):
'''parse sexp/S-expression format and return a python list'''
# define punctuation literals
LPAR, RPAR, LBRK, RBRK, LBRC, RBRC, VBAR = map(Suppress, "()[]{}|")
decimal = Word("123456789", nums).setParseAction(lambda t: int(t[0]))
bytes = Word(printables)
raw = Group(decimal.setResultsName("len") + Suppress(":") + bytes).setParseAction(OtrPrivateKeys.verifyLen)
token = Word(alphanums + "-./_:*+=")
base64_ = Group(Optional(decimal, default=None).setResultsName("len") + VBAR
+ OneOrMore(Word( alphanums +"+/=" )).setParseAction(lambda t: b64decode("".join(t)))
+ VBAR).setParseAction(OtrPrivateKeys.verifyLen)
hexadecimal = ("#" + OneOrMore(Word(hexnums)) + "#")\
.setParseAction(lambda t: int("".join(t[1:-1]),16))
qString = Group(Optional(decimal, default=None).setResultsName("len") +
dblQuotedString.setParseAction(removeQuotes)).setParseAction(OtrPrivateKeys.verifyLen)
simpleString = raw | token | base64_ | hexadecimal | qString
display = LBRK + simpleString + RBRK
string_ = Optional(display) + simpleString
sexp = Forward()
sexpList = Group(LPAR + ZeroOrMore(sexp) + RPAR)
sexp << ( string_ | sexpList )
try:
sexpr = sexp.parseString(data)
return sexpr.asList()[0][1:]
except ParseFatalException, pfe:
print("Error:", pfe.msg)
print(pfe.loc)
print(pfe.markInputline())
开发者ID:a-u-me,项目名称:keysync,代码行数:33,代码来源:otr_private_key.py
示例2: parse
def parse(string):
''' returns either [atomic], [monoop, [f]] or [binop, [f1], [f2]]
this method is static (no need for a CTL instance) '''
lparen = Literal('(').suppress()
rparen = Literal(')').suppress()
wildcard = Literal('_')
atom = Combine(Word(alphas) + Optional(Word('.0123456789'))
^ 'true' ^ 'false' ^ wildcard)
term = Forward()
term << (atom
+ Optional(lparen + Group(term)
+ ZeroOrMore(Literal(',').suppress() + Group(term))
+ rparen))
A = Optional('<-')+'A'
E = Optional('<-')+'E'
G, Gi, F, X, U = map(Literal, ('G', 'Gi', 'F', 'X', 'U'))
UnOp = wildcard ^ '!' ^ Combine(A + (G^F^X)) ^ Combine(E + (G^Gi^F^X))
BinOp = wildcard ^ Literal('or') ^ Literal('and') ^ Combine(A + U) ^ Combine(E + U)
formula = Forward()
formula << (Group(term)
^ (lparen + formula + rparen)
^ Group(UnOp + formula)
^ Group(BinOp + formula + formula))
# 0 because we expect only one formula in the string
return formula.parseString(string).asList()[0]
开发者ID:toumix,项目名称:eagle,代码行数:30,代码来源:ctl.py
示例3: parseQuery
def parseQuery(queryString):
try:
parser = Forward();
# parser << (Word(alphas).setResultsName( "first" ) + \
# #(' ').setResultsName( "delim" ) + \
# '*' + Word(alphas).setResultsName( "second"))
# selectSpecialStmt = Forward.setResultsName("selectSpecialStmt");
# selectSpecialStmt << (selectSpecialToken + "(" + table_columns + ")" + fromToken \
# + table.setResultsName("table"));
selectStmt = Forward().setResultsName("selectStmt");
selectStmt << ( selectToken + ( '*' | func_table_column | table_columns).setResultsName( "columns" ) \
+ fromToken + tables.setResultsName("tables") \
+ Optional(whereToken + whereExpression.setResultsName("conds") ) );
deleteStmt = Forward().setResultsName("deleteStmt");
deleteStmt << ( deleteToken + table.setResultsName("table") \
+ whereToken + whereExpression.setResultsName("conds"));
insertStmt = Forward().setResultsName("insertStmt");
insertStmt << ( insertToken + table.setResultsName("table") + valuesToken \
+ "(" + intNums.setResultsName("intValues") + ")" );
createStmt = Forward().setResultsName("createStmt");
createStmt << ( createToken + table.setResultsName("table") + "(" \
+ Group(delimitedList(column + intToken)).setResultsName("fields") + ")" );
truncateStmt = Forward().setResultsName("truncateStmt");
truncateStmt << ( truncateToken + table.setResultsName("table"));
dropStmt = Forward().setResultsName("dropStmt");
dropStmt << ( dropToken + table.setResultsName("table"));
parser = selectStmt | insertStmt | deleteStmt | createStmt | truncateStmt | dropStmt | exitToken;
tokens = parser.parseString(queryString);
# import pdb; pdb.set_trace()
return tokens
except Exception as e:
# print e;
print "Error in format."
return [];
开发者ID:chandan5,项目名称:mini-mysql,代码行数:34,代码来源:parse_query.py
示例4: __parseNestedList
def __parseNestedList( value, dtype = float):
from pyparsing import Word, Group, Forward, OneOrMore, Optional, alphanums, Suppress
number = Word( alphanums + ".e-" ).setParseAction( lambda s,l,t: dtype(t[0]) )
arr = Forward()
element = number | arr
arr << Group(Suppress('[') + ( OneOrMore(element + Optional(Suppress(",")) ) ) + Suppress(']') )
return arr.parseString(value, parseAll = True).asList()[0]
开发者ID:Haider-BA,项目名称:walberla,代码行数:7,代码来源:config.py
示例5: build_parser
def build_parser(root_directory, path, fake_root=os.getcwd(), file_reader=None):
from pyparsing import nestedExpr
from pyparsing import QuotedString
from pyparsing import Group
from pyparsing import restOfLine
from pyparsing import Word
from pyparsing import alphanums
from pyparsing import cStyleComment
from pyparsing import OneOrMore
from pyparsing import ZeroOrMore
from pyparsing import Optional
from pyparsing import Forward
from pyparsing import Literal
from pyparsing import Keyword
root = Forward()
include_handler = IncludeHandler(
root_directory,
path,
root,
fake_root=fake_root,
file_reader=file_reader)
# relaxed grammar
identifier = Word(alphanums + "-_.:/")
comment = ("//" + restOfLine).suppress() \
| ("#" + restOfLine).suppress() \
| cStyleComment
endstmt = Literal(";").suppress()
argument = QuotedString('"') \
| identifier
arguments = ZeroOrMore(argument)
statements = Forward()
section = nestedExpr("{", "}", statements)
include = Keyword("include").suppress() + QuotedString('"')
regular = identifier + Group(arguments) + Optional(section, default=[])
statement = include.setParseAction(include_handler.pyparsing_call) \
| regular.setParseAction(include_handler.pyparsing_mark)
statements << OneOrMore(statement + endstmt)
root << Optional(statements)
root.ignore(comment)
setattr(
root, 'parse_file',
lambda f, root=root: root.parseFile(f, parseAll=True))
return root
开发者ID:udoprog,项目名称:bsa,代码行数:60,代码来源:named.py
示例6: parse_constraint_group
def parse_constraint_group(constraint_group):
global valgrind_operations, size_by_var, offset_by_var, realsize_by_var, shift_by_var
init_global_vars()
lparen = Literal("(")
rparen = Literal(")")
func = Word(alphanums, alphanums+":_")
integer = Word(nums)
expression = Forward()
arg = expression | func | integer
args = arg + ZeroOrMore(","+arg)
expression << func + lparen + args + rparen
expression.setParseAction(parse_function)
valgrind_operations_group = []
for constraint in constraint_group:
valgrind_operations = []
expression.parseString(constraint)
resize_operands()
valgrind_operations_group.append(valgrind_operations)
return (valgrind_operations_group, size_by_var, offset_by_var, realsize_by_var, shift_by_var)
开发者ID:taveso,项目名称:Concolic-testing,代码行数:29,代码来源:parser.py
示例7: get_enclosed
def get_enclosed(self,raw):
#Word ::= Ascii - Tokens
non_token = "!#$%&\'*+,-./:;[email protected]\\^_`|~"
word = Word(alphanums+non_token)
#word = Word(printables)
#Tokens ::= {}[]()<>
tokens = "{}[]()<>"
o_curly,c_curly,o_brack,c_brack,o_paren,c_paren,o_mayor,c_mayor = map(Suppress,tokens)
enclosed_data = Forward()
#Enclosed groups
curly_enclosed = OneOrMore(o_curly + enclosed_data + c_curly)
brack_enclosed = OneOrMore(o_brack + enclosed_data + c_brack)
paren_enclosed = OneOrMore(o_paren + enclosed_data + c_paren)
mayor_enclosed = OneOrMore(o_mayor + enclosed_data + c_mayor)
enclosed = Optional(curly_enclosed) & Optional(brack_enclosed) & Optional(paren_enclosed) & Optional(mayor_enclosed)
enclosed_data << ((OneOrMore(word) & enclosed) ^ enclosed)
return enclosed_data.parseString(raw)
开发者ID:Epzylon,项目名称:EmailAnalizer,代码行数:25,代码来源:utils.py
示例8: parseATL
def parseATL(spec):
"""Parse the spec and return the list of possible ASTs."""
global __atl
if __atl 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]))
agent = atom
group = Group(ZeroOrMore(agent + Suppress(",")) + agent)
proposition = true | false | atom
__atl = Forward()
notproposition = "~" + proposition
notproposition.setParseAction(lambda tokens: Not(tokens[1]))
formula = (proposition | notproposition |
Suppress("(") + __atl + Suppress(")"))
logical = Forward()
cax = Literal("[") + group + "]" + "X" + logical
cax.setParseAction(lambda tokens: CAX(tokens[1], tokens[4]))
cex = Literal("<") + group + ">" + "X" + logical
cex.setParseAction(lambda tokens: CEX(tokens[1], tokens[4]))
caf = Literal("[") + group + "]" + "F" + logical
caf.setParseAction(lambda tokens: CAF(tokens[1], tokens[4]))
cef = Literal("<") + group + ">" + "F" + logical
cef.setParseAction(lambda tokens: CEF(tokens[1], tokens[4]))
cag = Literal("[") + group + "]" + "G" + logical
cag.setParseAction(lambda tokens: CAG(tokens[1], tokens[4]))
ceg = Literal("<") + group + ">" + "G" + logical
ceg.setParseAction(lambda tokens: CEG(tokens[1], tokens[4]))
cau = Literal("[") + group + "]" + "[" + __atl + "U" + __atl + "]"
cau.setParseAction(lambda tokens: CAU(tokens[1], tokens[4], tokens[6]))
ceu = Literal("<") + group + ">" + "[" + __atl + "U" + __atl + "]"
ceu.setParseAction(lambda tokens: CEU(tokens[1], tokens[4], tokens[6]))
caw = Literal("[") + group + "]" + "[" + __atl + "W" + __atl + "]"
caw.setParseAction(lambda tokens: CAW(tokens[1], tokens[4], tokens[6]))
cew = Literal("<") + group + ">" + "[" + __atl + "W" + __atl + "]"
cew.setParseAction(lambda tokens: CEW(tokens[1], tokens[4], tokens[6]))
strategic = (cax | cex | caf | cef | cag | ceg | cau | ceu | caw | cew)
logical <<= (formula | strategic)
__atl <<= (_logicals_(logical))
return __atl.parseString(spec, parseAll = True)
开发者ID:ancailliau,项目名称:pynusmv,代码行数:59,代码来源:parsing.py
示例9: bnf
def bnf(self):
'''
The BNF grammar is defined bellow.
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
'''
if not self._bnf:
point = Literal(".")
e = CaselessLiteral("E")
fnumber = Combine(
Word("+-"+nums, nums) +
Optional(point + Optional(Word(nums))) +
Optional(e + Word("+-" + nums, nums))
)
ident = Word(alphas, alphas + nums + "_$")
minus = Literal("-")
plus = Literal("+")
div = Literal("/")
mult = Literal("*")
rpar = Literal(")").suppress()
lpar = Literal("(").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
pi = CaselessLiteral("PI")
expr = Forward()
atom = (
Optional("-") +
(
pi |
e |
fnumber |
ident + lpar + delimitedList(expr) + rpar
).setParseAction(self.push_first) |
(lpar + expr.suppress() + rpar)
).setParseAction(self.push_minus)
# The right way to define exponentiation is -> 2^3^2 = 2^(3^2),
# not (2^3)^2.
factor = Forward()
factor << atom + ZeroOrMore(
(expop + factor).setParseAction(self.push_first)
)
term = factor + ZeroOrMore(
(multop + factor).setParseAction(self.push_first)
)
expr << term + ZeroOrMore(
(addop + term).setParseAction(self.push_first)
)
self._bnf = expr
return self._bnf
开发者ID:capensis,项目名称:canopsis,代码行数:59,代码来源:math_parser.py
示例10: compute
def compute(input_string):
# Debugging flag can be set to either "debug_flag=True" or "debug_flag=False"
debug_flag = False
explain_list = []
variables = {}
# define grammar
point = Literal(".")
e = CaselessLiteral("E")
plusorminus = Literal("+") | Literal("-")
number = Word(nums)
integer = Combine(Optional(plusorminus) + number)
floatnumber = Combine(integer + Optional(point + Optional(number)) + Optional(e + integer))
ident = Word(alphas, alphanums + "_")
plus = Literal("+")
minus = Literal("-")
mult = Literal("*")
div = Literal("/")
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
assign = Literal("=")
expr = Forward()
atom = (e | floatnumber | integer | ident).setParseAction(pushFirst) | (lpar + expr.suppress() + rpar)
factor = Forward()
factor << atom + ZeroOrMore((expop + factor).setParseAction(pushFirst))
term = factor + ZeroOrMore((multop + factor).setParseAction(pushFirst))
expr << term + ZeroOrMore((addop + term).setParseAction(pushFirst))
bnf = Optional((ident + assign).setParseAction(assignVar)) + expr
pattern = bnf + StringEnd()
if input_string != "":
try:
L = pattern.parseString(input_string)
except ParseException, err:
raise ComputationException, "Error while parsing"
print exprStack
if len(exprStack) <= 1:
return None
result = evaluateStack(exprStack, explain_list)
if len(str(result)) > 12:
ret = "%e" % result
else:
ret = str(result)
ret = ret.replace("e", " x 10^")
ret = ret.replace("+", "")
if len(explain_list):
return "%s (%s)" % (ret, ", ".join(explain_list))
else:
return "%s" % ret
开发者ID:iapain,项目名称:eviscapelite,代码行数:59,代码来源:arithmatic.py
示例11: parseArctl
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)
开发者ID:sbusard,项目名称:pynusmv,代码行数:58,代码来源:parsing.py
示例12: _string_to_ast
def _string_to_ast(self, input_string):
""" Parse a smart search string and return it in an AST like form
"""
# simple words
# we need to use a regex to match on words because the regular
# Word(alphanums) will only match on American ASCII alphanums and since
# we try to be Unicode / internationally friendly we need to match much
# much more. Trying to expand a word class to catch it all seems futile
# so we match on everything *except* a few things, like our operators
comp_word = Regex("[^*\s=><~!]+")
word = Regex("[^*\s=><~!]+").setResultsName('word')
# numbers
comp_number = Word(nums)
number = Word(nums).setResultsName('number')
# IPv4 address
ipv4_oct = Regex("((2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?))")
comp_ipv4_address = Combine(ipv4_oct + ('.' + ipv4_oct*3))
ipv4_address = Combine(ipv4_oct + ('.' + ipv4_oct*3)).setResultsName('ipv4_address')
# IPv6 address
ipv6_address = Regex("((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?").setResultsName('ipv6_address')
ipv6_prefix = Combine(ipv6_address + Regex("/(12[0-8]|1[01][0-9]|[0-9][0-9]?)")).setResultsName('ipv6_prefix')
# VRF RTs of the form number:number
vrf_rt = Combine((comp_ipv4_address | comp_number) + Literal(':') + comp_number).setResultsName('vrf_rt')
# tags
tags = Combine( Literal('#') + comp_word).setResultsName('tag')
# operators for matching
match_op = oneOf(' '.join(self.match_operators)).setResultsName('operator')
boolean_op = oneOf(' '.join(self.boolean_operators)).setResultsName('boolean')
# quoted string
d_quoted_string = QuotedString('"', unquoteResults=True, escChar='\\')
s_quoted_string = QuotedString('\'', unquoteResults=True, escChar='\\')
quoted_string = (s_quoted_string | d_quoted_string).setResultsName('quoted_string')
# expression to match a certain value for an attribute
expression = Group(word + match_op + (quoted_string | vrf_rt | word | number)).setResultsName('expression')
# we work on atoms, which are single quoted strings, match expressions,
# tags, VRF RT or simple words.
# NOTE: Place them in order of most exact match first!
atom = Group(ipv6_prefix | ipv6_address | quoted_string | expression | tags | vrf_rt | boolean_op | word)
enclosed = Forward()
parens = nestedExpr('(', ')', content=enclosed)
enclosed << (
parens | atom
).setResultsName('nested')
content = Forward()
content << (
ZeroOrMore(enclosed)
)
res = content.parseString(input_string)
return res
开发者ID:fredsod,项目名称:NIPAP,代码行数:58,代码来源:smart_parsing.py
示例13: _BNF
def _BNF(self):
base16 = Literal("$")
hex = Combine(base16 + Word(hexnums + "_"))
base4 = Literal("%%")
quaternary = Combine(base4 + Word("0123_"))
base2 = Literal("%")
binary = Combine(base2 + Word("01_"))
plusminus = Literal("+") | Literal("-")
integer = Combine(Optional(plusminus) + Word(nums+"_"))
name_token = Combine(Optional(Literal(":") | Literal("@")) + Word("_" + alphas, "_" + alphanums))
name_token.setParseAction(self._mark_name_token)
lparens = Literal("(").suppress()
rparens = Literal(")").suppress()
# op0 = Literal("@")
op1 = (Literal("^^") | Literal("||") | Literal("|<") | Literal(">|") | Literal("!")).setParseAction(self._mark_unary)
op2 = Literal("->") | Literal("<-") | Literal(">>") | Literal("<<") | Literal("~>") | Literal("><")
op3 = Literal("&")
op4 = Literal("|") | Literal("^")
op5 = Literal("**") | Literal("*") | Literal("//") | Literal("/")
op6 = Literal("+") | Literal("-")
op7 = Literal("#>") | Literal("<#")
op8 = Literal("<") | Literal(">") | Literal("<>") | Literal("==") | Literal("=<") | Literal("=>")
op9 = Literal("NOT").setParseAction(self._mark_unary)
op10 = Literal("AND")
op11 = Literal("OR")
op12 = Literal(",")
expr = Forward()
atom = name_token | hex | quaternary | binary | integer | quotedString
atom.setParseAction(self._push)
atom = atom | (lparens + expr.suppress() + rparens)
# term0 = atom + ZeroOrMore((op0 + atom) .setParseAction(self._push))
# term1 = term0 + ZeroOrMore((op1 + term0) .setParseAction(self._push))
term1 = atom + ZeroOrMore((op1 + atom) .setParseAction(self._push))
term2 = term1 + ZeroOrMore((op2 + term1) .setParseAction(self._push))
term3 = term2 + ZeroOrMore((op3 + term2) .setParseAction(self._push))
term4 = term3 + ZeroOrMore((op4 + term3) .setParseAction(self._push))
term5 = term4 + ZeroOrMore((op5 + term4) .setParseAction(self._push))
term6 = term5 + ZeroOrMore((op6 + term5) .setParseAction(self._push))
term7 = term6 + ZeroOrMore((op7 + term6) .setParseAction(self._push))
term8 = term7 + ZeroOrMore((op8 + term7) .setParseAction(self._push))
term9 = term8 + ZeroOrMore((op9 + term8) .setParseAction(self._push))
term10 = term9 + ZeroOrMore((op10 + term9) .setParseAction(self._push))
term11 = term10 + ZeroOrMore((op11 + term10).setParseAction(self._push))
expr << term11 + ZeroOrMore((op12 + term11).setParseAction(self._push))
return expr
开发者ID:Seairth,项目名称:Orochi,代码行数:55,代码来源:expression.py
示例14: parser
def parser():
rule = Forward()
body = OneOrMore(CharsNotIn('{};') + ';')
sel = CharsNotIn('{};')
rule <<= sel + Group( '{' + ZeroOrMore( rule | body ) + '}' )
rule.setParseAction( make_action(Rule) )
stylesheet = ZeroOrMore( rule )
stylesheet.ignore( cStyleComment )
return stylesheet
开发者ID:svbatalov,项目名称:css-extract,代码行数:12,代码来源:parse.py
示例15: main
def main(s):
lpar = Literal('(').suppress()
rpar = Literal(')').suppress()
integer = Word(nums)
element = Word(alphas, exact=1)
formula = Forward()
term = Group((element | Group(lpar + formula + rpar)('subgroup')) +
Optional(integer, default=1)('mult'))
formula << OneOrMore(term)
integer.setParseAction(process_integer)
term.setParseAction(process_term)
formula.setParseAction(process_formula)
return formula.parseString(s)[0]
开发者ID:argriffing,项目名称:hp,代码行数:13,代码来源:expand-nested.py
示例16: _BNF
def _BNF(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
if not self.bnf:
point = Literal( "." )
e = CaselessLiteral( "E" )
fnumber = Combine( Word( "+-"+nums, nums ) +
Optional( point + Optional( Word( nums ) ) ) +
Optional( e + Word( "+-"+nums, nums ) ) )
ident = Word(alphas, alphas+nums+"_$")
plus = Literal( "+" )
minus = Literal( "-" )
mult = Literal( "*" )
div = Literal( "/" )
lpar = Literal( "(" ).suppress()
rpar = Literal( ")" ).suppress()
# comma = Literal( "," ).suppress()
comma = Literal( "," )
addop = plus | minus
multop = mult | div
expop = Literal( "^" )
pi = CaselessLiteral( "PI" )
var_list = [Literal(i) for i in self.var_names]
expr = Forward()
arg_func = Forward()
or_vars = MatchFirst(var_list)
# atom = (Optional("-") + ( pi | e | fnumber | ident + lpar + delimitedList(Group(expr)) + rpar | or_vars ).setParseAction( self._pushFirst ) | ( lpar + delimitedList(Group(expr)).suppress() + rpar ) ).setParseAction(self._pushUMinus)
atom = ((Optional("-") + ( pi | e | fnumber | ident + lpar + arg_func + rpar | or_vars ).setParseAction( self._pushFirst )) | \
(Optional("-") + ( lpar + arg_func.suppress() + rpar )) ).setParseAction(self._pushUMinus)
# expr + ZeroOrMore( "," + expr )
# by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-righ
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( self._pushFirst ) )
term = factor + ZeroOrMore( ( multop + factor ).setParseAction( self._pushFirst ) )
expr << term + ZeroOrMore( ( addop + term ).setParseAction( self._pushFirst ) )
arg_func << expr + ZeroOrMore( (comma + expr).setParseAction( self._pushFirst))
self.bnf = expr
return self.bnf
开发者ID:MelkoCollective,项目名称:casini_corners,代码行数:51,代码来源:math_parse.py
示例17: parser
def parser(text):
"""
str := \w+
str := '\w+'
exp := Var=str
exp := exp & exp
exp := exp ^ exp
"""
# grammar
#g_string = "'"+Word(alphas)+"'" | Word(alphas)
g_quote = Literal("'").suppress()
g_text = Regex("[\w\s\:\#\.]+").setResultsName("text")
g_string = Optional(g_quote) + g_text + Optional(g_quote)
g_equ = Literal("!=").setResultsName("connector") | Literal("=").setResultsName("connector")
g_amp = Literal("&").setResultsName("connector")
g_hat = Literal("^").setResultsName("connector")
g_or = Literal("|").suppress()
g_seq = Literal("->").setResultsName("connector")
g_hash = Literal("#").setResultsName("hash")
g_left_brack = Literal("[").suppress()
g_right_brack = Literal("]").suppress()
g_vals = Forward()
g_vals << g_string + ZeroOrMore(Group(g_or + g_vals).setResultsName("or_group"))
# working
"""
exp_basic = Group(Optional(g_hash) + g_string).setResultsName("left") + g_equ + Group(g_vals).setResultsName("right")
exp = Group(exp_basic)
exp = exp.setResultsName("left") + g_amp + exp.setResultsName("right") | \
g_left_brack + exp.setResultsName("left") + g_hat + exp.setResultsName("right") + g_right_brack | \
g_left_brack + exp.setResultsName("left") + g_seq + exp.setResultsName("right") + g_right_brack | \
exp_basic
"""
# recursion
simpleq = Forward()
complexq = Forward()
exp = (simpleq | complexq).setResultsName("exp")
exp_basic = Group(Group(Optional(g_hash) + g_string).setResultsName("left") + g_equ + Group(g_vals).setResultsName("right"))
simpleq << (Group(exp_basic.setResultsName("left") + g_amp + simpleq.setResultsName("right")) | exp_basic)
complexq << ( Group(g_left_brack + exp.setResultsName("left") + g_hat + exp.setResultsName("right") + g_right_brack) | \
Group(g_left_brack + exp.setResultsName("left") + g_seq + exp.setResultsName("right") + g_right_brack) )
return exp.parseString(text)
开发者ID:incognybble,项目名称:toSPARQL,代码行数:51,代码来源:emu_parser.py
示例18: parse
def parse (input):
# parse a string into an element of the abstract representation
# Grammar:
#
# <expr> ::= <integer>
# true
# false
# <identifier>
# ( if <expr> <expr> <expr> )
# ( let ( ( <name> <expr> ) ) <expr )
# ( + <expr> <expr> )
# ( * <expr> <expr> )
#
idChars = alphas+"_+*-?!=<>"
pIDENTIFIER = Word(idChars, idChars+"0123456789")
pIDENTIFIER.setParseAction(lambda result: EId(result[0]))
# A name is like an identifier but it does not return an EId...
pNAME = Word(idChars,idChars+"0123456789")
pINTEGER = Word("-0123456789","0123456789")
pINTEGER.setParseAction(lambda result: EInteger(int(result[0])))
pBOOLEAN = Keyword("true") | Keyword("false")
pBOOLEAN.setParseAction(lambda result: EBoolean(result[0]=="true"))
pEXPR = Forward()
pIF = "(" + Keyword("if") + pEXPR + pEXPR + pEXPR + ")"
pIF.setParseAction(lambda result: EIf(result[2],result[3],result[4]))
pBINDING = "(" + pNAME + pEXPR + ")"
pBINDING.setParseAction(lambda result: (result[1],result[2]))
pLET = "(" + Keyword("let") + "(" + pBINDING + ")" + pEXPR + ")"
pLET.setParseAction(lambda result: ELet([result[3]],result[5]))
pPLUS = "(" + Keyword("+") + pEXPR + pEXPR + ")"
pPLUS.setParseAction(lambda result: ECall("+",[result[2],result[3]]))
pTIMES = "(" + Keyword("*") + pEXPR + pEXPR + ")"
pTIMES.setParseAction(lambda result: ECall("*",[result[2],result[3]]))
pEXPR << (pINTEGER | pBOOLEAN | pIDENTIFIER | pIF | pLET | pPLUS | pTIMES)
result = pEXPR.parseString(input)[0]
return result # the first element of the result is the expression
开发者ID:rpucella,项目名称:rpucella.github.io,代码行数:51,代码来源:homework3.py
示例19: sandbox
def sandbox():
"""Based on http://stackoverflow.com/a/4802004/623735"""
loose_grammar = Forward()
nestedParens = nestedExpr('(', ')', content=loose_grammar)
loose_grammar << (
OneOrMore(Optional(':').suppress() + Word(alphanums + '-_'))
| OneOrMore(Optional('?').suppress() + Word(alphanums + '-_'))
| init
| goal
| ','
| nestedParens)
examples = [
# definitely not PDDL-compliant, but parser does OK anyway (not strict)
'(some global things (:a (nested list of three varibles (?list0 ?list1 ?list2))))',
# this is a valid line of STRIPS (subset of PDDL grammar?)
'(:requirements :strips)',
# another valid line of STRIPS (subset of PDDL grammar?)
'(define (domain random-domain))',
# a complete (if simple) STRIPS problem definition from coursera AI Planning class, HW wk2
r'''
(define (problem random-pbl1)
(:domain random-domain)
(:init
(S B B) (S C B) (S A C)
(R B B) (R C B))
(:goal (and (S A A))))
''',
# a complete STRIPS domain definition from coursera AI Planning class, HW wk2
r'''
(define (domain random-domain)
(:requirements :strips)
(:action op1
:parameters (?x1 ?x2 ?x3)
:precondition (and (S ?x1 ?x2) (R ?x3 ?x1))
:effect (and (S ?x2 ?x1) (S ?x1 ?x3) (not (R ?x3 ?x1))))
(:action op2
:parameters (?x1 ?x2 ?x3)
:precondition (and (S ?x3 ?x1) (R ?x2 ?x2))
:effect (and (S ?x1 ?x3) (not (S ?x3 ?x1)))))
''',
]
ans = []
for ex in examples:
try:
ans += [loose_grammar.parseString(ex).asList()]
print(ans[-1])
except:
print_exc()
return ans
开发者ID:WeDoKnowWhy151,项目名称:coursera,代码行数:49,代码来源:pddl.py
示例20: __init__
def __init__(self, query):
self._methods = {
|
请发表评论