本文整理汇总了Python中pyparsing.Literal类的典型用法代码示例。如果您正苦于以下问题:Python Literal类的具体用法?Python Literal怎么用?Python Literal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Literal类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_disable_pyparsing_arity_trimming_works
def test_disable_pyparsing_arity_trimming_works():
"""Tests that arity trimming has been disabled and parse actions with
the wrong number of arguments will raise TypeErrors"""
for func in [lambda a: None, lambda a, b: None, lambda a, b, c, d: None]:
element = Literal('test').setParseAction(func)
with raises(TypeError):
element.parseString('test')
开发者ID:borntyping,项目名称:python-dice,代码行数:7,代码来源:test_utilities.py
示例2: parser
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
开发者ID:Bernie,项目名称:spyne,代码行数:34,代码来源:invregexp.py
示例3: _logical_parser
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
开发者ID:sbusard,项目名称:PyTLQ,代码行数:31,代码来源:parser.py
示例4: __init__
def __init__(self):
from pyparsing import (ParserElement, StringEnd, LineEnd, Literal,
pythonStyleComment, ZeroOrMore, Suppress,
Optional, Combine, OneOrMore, Regex, oneOf,
QuotedString, Group, ParseException)
ParserElement.setDefaultWhitespaceChars("\t ")
EOF = StringEnd()
EOL = ~EOF + LineEnd() # EOL must not match on EOF
escape = Literal("\\")
comment = pythonStyleComment
junk = ZeroOrMore(comment | EOL).suppress()
## word (i.e: single argument string)
word = Suppress(escape + EOL + Optional(comment)) \
| Combine(OneOrMore( escape.suppress() + Regex(".") |
QuotedString("'", escChar='\\', multiline=True) |
QuotedString('"', escChar='\\', multiline=True) |
Regex("[^ \t\r\n\f\v\\\\$&<>();\|\'\"`]+") |
Suppress(escape + EOL) ))
## redirector (aka bash file redirectors, such as "2>&1" sequences)
fd_src = Regex("[0-2]").setParseAction(lambda t: int(t[0]))
fd_dst = Suppress("&") + fd_src
# "[n]<word" || "[n]<&word" || "[n]<&digit-"
fd_redir = (Optional(fd_src, 0) + Literal("<")
|Optional(fd_src, 1) + Literal(">"))\
+(word | (fd_dst + Optional("-")))
# "&>word" || ">&word"
full_redir = (oneOf("&> >&") + word)\
.setParseAction(lambda t:("&" ,">", t[-1]))
# "<<<word" || "<<[-]word"
here_doc = Regex("<<(<|-?)") + word
# "[n]>>word"
add_to_file = Optional(fd_src | Literal("&"), 1) + \
Literal(">>") + word
# "[n]<>word"
fd_bind = Optional(fd_src, 0) + Literal("<>") + word
redirector = (fd_redir | full_redir | here_doc
| add_to_file | fd_bind)\
.setParseAction(lambda token: tuple(token))
## single command (args/redir list)
command = Group(OneOrMore(redirector | word))
## logical operators (section splits)
semicolon = Suppress(";") + junk
connector = (oneOf("&& || |") + junk) | semicolon
## pipeline, aka logical block of interconnected commands
pipeline = junk + Group(command +
ZeroOrMore(connector + command) +
Optional(semicolon))
# define object attributes
self.LEXER = pipeline.ignore(comment) + EOF
self.parseException = ParseException
开发者ID:0x0mar,项目名称:phpsploit,代码行数:60,代码来源:lexer.py
示例5: __init__
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)
开发者ID:odahoda,项目名称:noisicaa,代码行数:26,代码来源:sfzparser.py
示例6: _define_valued_characters_section
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
开发者ID:ajenhl,项目名称:zounds,代码行数:30,代码来源:binary_features_model_parser.py
示例7: _define_context_component
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
开发者ID:ajenhl,项目名称:zounds,代码行数:7,代码来源:ruleset_parser.py
示例8: define_number
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
开发者ID:aipub,项目名称:booleano,代码行数:34,代码来源:parsers.py
示例9: check_main_syntax
def check_main_syntax(self, code):
# Return value for main is optional in C++11
parser = Literal("int") + Literal("main") + Literal("(") + SkipTo(Literal(")")) + Literal(")")
if len(parser.searchString(code)):
main_prefix = Literal("int") + Literal("main") + Literal("(")
full_use = Literal("int") + "argc" + "," + Optional("const") + "char" + "*" + "argv" + "[" + "]" + ")"
# 3 options for main() syntax
if not len((main_prefix + Literal(")")).searchString(code)) and \
not len((main_prefix + Literal("void") + Literal(")")).searchString(code)) and \
not len((main_prefix + full_use).searchString(code)):
self.add_error(label="MAIN_SYNTAX")
开发者ID:vianuevm,项目名称:cppStyle,代码行数:11,代码来源:single_line_checks.py
示例10: check_function_def_above_main
def check_function_def_above_main(self, code):
prototype = check_if_function_prototype(code)
function = check_if_function(code)
inside = Literal("int main")
if len(inside.searchString(code)):
return
elif function and not prototype and self.outside_main:
function_regex = re.compile("^\s*(\w+)\s+(\w+)")
match = function_regex.search(code)
function_name = match.group(2) if match else "NOT_FOUND"
self.add_error(label="DEFINITION_ABOVE_MAIN", data={'function': function_name})
开发者ID:vianuevm,项目名称:cppStyle,代码行数:11,代码来源:single_line_checks.py
示例11: _getPattern
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
开发者ID:ArnoldOchieng,项目名称:echo-sense,代码行数:54,代码来源:expressionParser.py
示例12: check_unnecessary_include
def check_unnecessary_include(self, code):
grammar = Literal('#') + Literal('include') + Literal('<') + Word(alphanums)
try:
grammar.parseString(code)
begin = code.find("<")
end = code.find(">")
included_library = code[begin + 1:end]
if included_library not in self.includes:
self.add_error(label="UNNECESSARY_INCLUDE")
except ParseException:
return
开发者ID:vianuevm,项目名称:cppStyle,代码行数:11,代码来源:single_line_checks.py
示例13: check_main_prefix
def check_main_prefix(self, code):
#Return value for main is optional in C++11
parser = Literal("main")+Literal("(")+SkipTo(Literal(")"))+Literal(")")+Literal("{")
if len(parser.searchString(code)):
main_prefix = Literal("main")+Literal("(")
full_use = "int"+Word(alphanums)+","+"char*"+Word(alphanums)+"["+"]"+")"
# 3 options for main() syntax
if not len((main_prefix+Literal(")")).searchString(code)) and \
not len((main_prefix+Literal("void")+Literal(")")).searchString(code)) and \
not len((main_prefix+full_use).searchString(code)):
self.add_error("MAIN_SYNTAX")
开发者ID:reedcoke,项目名称:183_style_grader,代码行数:11,代码来源:StyleRubric.py
示例14: check_local_include
def check_local_include(self, code):
grammar = Literal('#') + Literal('include') + Literal('"') + Word(alphanums)
try:
grammar.parseString(code)
begin = code.find('"')
included_file = code[begin + 1:]
end = included_file.find('"')
included_file = included_file[:end]
if included_file not in self.includes:
self.local_includes[self.current_file].append(included_file)
except ParseException:
return
开发者ID:vianuevm,项目名称:cppStyle,代码行数:12,代码来源:single_line_checks.py
示例15: __init__
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")
开发者ID:ccr-tools,项目名称:aur2ccr,代码行数:13,代码来源:pkgbuild_parser.py
示例16: get_parser
def get_parser():
"""Return a section parser. @see grammar.md for the whole grammar."""
if Section._parser is None:
# Parser not yet defined. Defining it.
head_type = Literal("V") | Literal("C") | Literal("@")
head = OPEN_HEAD \
+ head_type.setResultsName("type") \
+ INTEGER.setResultsName("id") \
+ CLOSE_HEAD + EOL
content_line = WORDS + EOL
content = OneOrMore(content_line)
Section._parser = Group(head + content.setResultsName("content"))
return Section._parser
开发者ID:yapper-git,项目名称:liblyrics,代码行数:13,代码来源:section.py
示例17: get_log_formats
def get_log_formats(config):
"""
Parse config for log_format directives
:return: iterator over ('format name', 'format string') tuple of found directives
"""
# log_format name [params]
log_format = Literal('log_format') + parameter + Group(OneOrMore(parameter)) + semicolon
log_format.ignore(pythonStyleComment)
for directive in log_format.searchString(config).asList():
name = directive[1]
format_string = ''.join(directive[2])
yield name, format_string
开发者ID:healthly,项目名称:ngxtop,代码行数:13,代码来源:config_parser.py
示例18: check_non_const_global
def check_non_const_global(self, code):
inside = Literal("int main")
if len(inside.searchString(code)):
self.outside_main = False
if self.outside_main:
function = check_if_function(code)
variables = variables = re.compile("^(?:\w|_)+\s+(?:\w|_|\[|\])+\s*=\s*.+;")
keywords = re.compile("^\s*(?:using|class|struct)")
constants = re.compile("^\s*(?:static\s+)?const")
if not function and variables.search(code) and \
not keywords.search(code) and \
not constants.search(code):
self.add_error(label="NON_CONST_GLOBAL")
开发者ID:vianuevm,项目名称:cppStyle,代码行数:14,代码来源:single_line_checks.py
示例19: getkw_bnf
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
开发者ID:juselius,项目名称:libgetkw,代码行数:49,代码来源:getkw.py
示例20: fromString
def fromString(inputText, verbose=False):
if verbose: print 'Verbose:', verbose
text = nestedExpr("/*", "*/").suppress().transformString(inputText)
semicolon = Suppress(Word(";"))
quote = Suppress(Word("\""))
op = Suppress(Word("{"))
cl = Suppress(Word("}"))
opp = Suppress(Word("("))
clp = Suppress(Word(")"))
lt = Suppress(Word("<"))
gt = Suppress(Word(">"))
identifier = Word(alphas+"_",alphanums+"_")
typeIdentifier = Word(alphas+"_",alphanums+"_:")
## Imports
idslImport = Suppress(Word("import")) + quote + CharsNotIn("\";").setResultsName('path') + quote + semicolon
idslImports = ZeroOrMore(idslImport)
dictionaryDef = Word("dictionary") + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
sequenceDef = Word("sequence") + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
enumDef = Word("enum") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
structDef = Word("struct") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
exceptionDef = Word("exception") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
raiseDef = Suppress(Word("throws")) + typeIdentifier + ZeroOrMore( Literal(',') + typeIdentifier )
decoratorDef = Literal('idempotent') | Literal('out')
retValDef = typeIdentifier.setResultsName('ret')
firstParam = Group( Optional(decoratorDef.setResultsName('decorator')) + typeIdentifier.setResultsName('type') + identifier.setResultsName('name'))
nextParam = Suppress(Word(',')) + firstParam
params = firstParam + ZeroOrMore(nextParam)
remoteMethodDef = Group(Optional(decoratorDef) + retValDef + typeIdentifier.setResultsName('name') + opp + Optional( params).setResultsName('params') + clp + Optional(raiseDef) + semicolon )
interfaceDef = Word("interface") + typeIdentifier.setResultsName('name') + op + Group(ZeroOrMore(remoteMethodDef)) + cl + semicolon
moduleContent = Group(structDef | enumDef | exceptionDef | dictionaryDef | sequenceDef | interfaceDef)
module = Suppress(Word("module")) + identifier.setResultsName("name") + op + ZeroOrMore(moduleContent).setResultsName("contents") + cl + semicolon
IDSL = idslImports.setResultsName("imports") + module.setResultsName("module")
IDSL.ignore( cppStyleComment )
tree = IDSL.parseString(text)
return IDSLParsing.module(tree)
开发者ID:BasilMVarghese,项目名称:robocomp,代码行数:46,代码来源:parseIDSL.py
注:本文中的pyparsing.Literal类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论