本文整理汇总了Python中pyparsing.ZeroOrMore.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python ZeroOrMore.parseString方法的具体用法?Python ZeroOrMore.parseString怎么用?Python ZeroOrMore.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.ZeroOrMore
的用法示例。
在下文中一共展示了ZeroOrMore.parseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_macro_arguments
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def parse_macro_arguments(argument_string, return_kwargs=False):
if not argument_string:
return None
import re
from pyparsing import Group, Or, QuotedString, Regex, Suppress, ZeroOrMore
# General argument string parser
argstring_def = ZeroOrMore(Or([ \
QuotedString('"'), # long arguments
Group(Regex('[\w]+', flags=re.UNICODE) + # keyword arguments
Suppress('=').leaveWhitespace() +
Or([Regex('[\w]+'), QuotedString('"')])),
Regex(r'\(\(.*\)\)', flags=re.UNICODE), # nested macros
Regex('[\S]+', flags=re.UNICODE) # basic arguments
]))
args = argstring_def.parseString(argument_string).asList()
# The keyword arguments are stored as lists in the `args' variable,
# extract them and convert them into a dict, then return
if return_kwargs:
kwargs = {}
for arg in args:
if isinstance(arg, list):
kwargs[str(arg[0])] = arg[1]
args.remove(arg) # remove the nested list
return args, kwargs
return args
示例2: test_prefixed_line
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def test_prefixed_line(self):
parser = ZeroOrMore(comment | empty_line) + prefixed_line("Foo:") + ZeroOrMore(comment | empty_line)
foo = prefixed_line("Foo:")
self.assertEqual(parser.parseString("Foo: bar\n\n\n", True).asList(),
["bar", "<EMPTYLINE>", "<EMPTYLINE>", "<EMPTYLINE>"])
self.assertEqual(parser.parseString("Foo: bar \n\n\n", True).asList(),
["bar", "<EMPTYLINE>", "<EMPTYLINE>", "<EMPTYLINE>"])
self.assertEqual(parser.parseString("Foo: bar baz\n\n\n", True).asList(),
["bar baz", "<EMPTYLINE>", "<EMPTYLINE>", "<EMPTYLINE>"])
self.assertEqual(parser.parseString("Foo: bar \n \n", True).asList(),
["bar", "<EMPTYLINE>", "<EMPTYLINE>"])
self.assertEqual(parser.parseString("Foo: bar \n#baz\n #spam\n", True).asList(),
["bar", "<COMMENT>", "<COMMENT>", "<EMPTYLINE>"])
bar = parser + prefixed_line("Bar:") + ZeroOrMore(comment | empty_line)
self.assertEqual(bar.parseString("Foo: bar \n#baz\nBar: baz spam\n #spam\n", True).asList(),
["bar", "<COMMENT>", "baz spam", "<COMMENT>", "<EMPTYLINE>"])
示例3: _parse_items
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def _parse_items(self, source):
ParserElement.setDefaultWhitespaceChars(' \t\r')
EOL = LineEnd().suppress()
comment = Literal('#') + Optional( restOfLine ) + EOL
string = CharsNotIn("\n")
line = Group(
Word(alphanums + '-')('key') + Literal(':').suppress() + Optional(Combine(string + ZeroOrMore(EOL + Literal(' ') + string)))("value") + EOL
)
group = ZeroOrMore(line)
group.ignore(comment)
return group.parseString(source, True)
示例4: parse_template
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def parse_template(template_text):
identifier = Word(alphas, alphanums + '_')
param = Group(identifier('name') + Suppress(':') + CharsNotIn(',)')('value'))
param_list = Group(Suppress('(') + delimitedList(param, delim=',') + Suppress(')'))
benchmark_id = originalTextFor(identifier + '.' + identifier + '.' + identifier)
measurement_id = Group(benchmark_id('benchmark') + Optional(param_list('params')) + Suppress('[') + identifier('local_id') + Suppress(']'))
macro = Group(Suppress('${') + measurement_id('measurement') + Suppress('}'))
raw_text_block = originalTextFor(CharsNotIn('$'))
text = ZeroOrMore(Group(raw_text_block('text') | macro('macro')))('template')
text.leaveWhitespace()
return text.parseString(template_text).asDict()
示例5: guess_language
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def guess_language(string=None, filename=None):
"""
Attempt to guess the language
Do this by parsing the comments at the top of the file for the
# language: fr
phrase.
"""
LANG_PARSER = ZeroOrMore(
Suppress('#') + (
((Suppress(Keyword('language')) + Suppress(':') +
Word(unicodePrintables)('language')) |
Suppress(restOfLine))
)
)
try:
if string:
tokens = LANG_PARSER.parseString(string)
elif filename:
with open(filename, 'r', 'utf-8') as fp:
tokens = LANG_PARSER.parseFile(fp)
else:
raise RuntimeError("Must pass string or filename")
code = tokens.language
if code != '':
return languages.Language(code=code)
except ParseException as e:
# try English
pass
return languages.English()
示例6: Group
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
ellipticalArc = Group(Command("A") + Arguments(Sequence(ellipticalArcArgument)))
smoothQuadraticBezierCurveto = Group(Command("T") + Arguments(coordinatePairSequence))
quadraticBezierCurveto = Group(Command("Q") + Arguments(coordinatePairPairSequence))
smoothCurve = Group(Command("S") + Arguments(coordinatePairPairSequence))
#curve = Group(Command("C") + Arguments(coordinatePairTripleSequence))
horizontalLine = Group(Command("H") + Arguments(coordinateSequence))
verticalLine = Group(Command("V") + Arguments(coordinateSequence))
drawToCommand = (
lineTo | moveTo | closePath | ellipticalArc | smoothQuadraticBezierCurveto |
quadraticBezierCurveto | smoothCurve | curve | horizontalLine | verticalLine
)
#~ number.debug = True
moveToDrawToCommands = moveTo + ZeroOrMore(drawToCommand)
parser = ZeroOrMore(moveToDrawToCommands)
parser.keepTabs = True
import sys
if __name__ == "__main__":
# EX: print parser.parseString("M 242.96145,653.59282 L 244.83646,650.1553 L 247.02397,649.8428 L 247.33647,650.62405 L 245.30521,653.59282 L 242.96145,653.59282 z M 252.80525,649.99905 L 258.74278,652.49906 L 260.77404,652.18656 L 262.33654,648.43654 L 261.71154,645.15528 L 257.64902,644.68653 L 253.74275,646.40528 L 252.80525,649.99905 z M 282.49289,659.6866 L 286.08665,664.99912 L 288.43041,664.68662 L 289.52417,664.21787 L 290.93042,665.46787 L 294.52419,665.31162 L 295.4617,663.90537 L 292.64918,662.18661 L 290.77417,658.59284 L 288.74291,655.15533 L 283.11789,657.96784 L 282.49289,659.6866 z M 302.02423,668.28039 L 303.27423,666.40538 L 307.8055,667.34288 L 308.43051,666.87413 L 314.36803,667.49913 L 314.05553,668.74914 L 311.55552,670.15539 L 307.33675,669.84289 L 302.02423,668.28039 z M 307.1805,673.28041 L 309.05551,677.03043 L 312.02427,675.93667 L 312.33677,674.37416 L 310.77427,672.3429 L 307.1805,672.0304 L 307.1805,673.28041 z M 313.89928,672.18665 L 316.08679,669.37414 L 320.61806,671.7179 L 324.83683,672.81166 L 329.0556,675.46792 L 329.0556,677.34293 L 325.61809,679.06169 L 320.93056,679.99919 L 318.5868,678.59293 L 313.89928,672.18665 z M 329.99311,687.18672 L 331.55561,685.93672 L 334.83688,687.49923 L 342.18066,690.93674 L 345.46193,692.968 L 347.02443,695.31176 L 348.89944,699.53053 L 352.80571,702.03054 L 352.49321,703.28055 L 348.74319,706.40556 L 344.68067,707.81182 L 343.27442,707.18682 L 340.30565,708.90557 L 337.96189,712.03059 L 335.77438,714.8431 L 334.05562,714.68685 L 330.61811,712.18684 L 330.30561,707.81182 L 330.93061,705.46806 L 329.3681,699.99928 L 327.33684,698.28052 L 327.18059,695.78051 L 329.3681,694.84301 L 331.39936,691.87425 L 331.86811,690.93674 L 330.30561,689.21798 L 329.99311,687.18672 z ")
print parser.parseString(sys.argv[1])
示例7: parse
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
#.........这里部分代码省略.........
)
elif file is not None:
path = file if basedir is None else os.path.join(basedir, file)
logger.debug('Loading config from file %s', path)
obj = ConfigFactory.parse_file(
path,
resolve=False,
required=required,
unresolved_value=NO_SUBSTITUTION
)
else:
raise ConfigException('No file or URL specified at: {loc}: {instring}', loc=loc, instring=instring)
return ConfigInclude(obj if isinstance(obj, list) else obj.items())
@contextlib.contextmanager
def set_default_white_spaces():
default = ParserElement.DEFAULT_WHITE_CHARS
ParserElement.setDefaultWhitespaceChars(' \t')
yield
ParserElement.setDefaultWhitespaceChars(default)
with set_default_white_spaces():
assign_expr = Forward()
true_expr = Keyword("true", caseless=True).setParseAction(replaceWith(True))
false_expr = Keyword("false", caseless=True).setParseAction(replaceWith(False))
null_expr = Keyword("null", caseless=True).setParseAction(replaceWith(NoneValue()))
key = QuotedString('"', escChar='\\', unquoteResults=False) | Word(alphanums + alphas8bit + '._- /')
eol = Word('\n\r').suppress()
eol_comma = Word('\n\r,').suppress()
comment = (Literal('#') | Literal('//')) - SkipTo(eol | StringEnd())
comment_eol = Suppress(Optional(eol_comma) + comment)
comment_no_comma_eol = (comment | eol).suppress()
number_expr = Regex(r'[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE][+\-]?\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))',
re.DOTALL).setParseAction(convert_number)
period_types = itertools.chain.from_iterable(cls.get_supported_period_type_map().values())
period_expr = Regex(r'(?P<value>\d+)\s*(?P<unit>' + '|'.join(period_types) + ')$'
).setParseAction(convert_period)
# multi line string using """
# Using fix described in http://pyparsing.wikispaces.com/share/view/3778969
multiline_string = Regex('""".*?"*"""', re.DOTALL | re.UNICODE).setParseAction(parse_multi_string)
# single quoted line string
quoted_string = Regex(r'"(?:[^"\\\n]|\\.)*"[ \t]*', re.UNICODE).setParseAction(create_quoted_string)
# unquoted string that takes the rest of the line until an optional comment
# we support .properties multiline support which is like this:
# line1 \
# line2 \
# so a backslash precedes the \n
unquoted_string = Regex(r'(?:[^^`[email protected]*&"\[\{\s\]\}#,=\$\\]|\\.)+[ \t]*', re.UNICODE).setParseAction(unescape_string)
substitution_expr = Regex(r'[ \t]*\$\{[^\}]+\}[ \t]*').setParseAction(create_substitution)
string_expr = multiline_string | quoted_string | unquoted_string
value_expr = period_expr | number_expr | true_expr | false_expr | null_expr | string_expr
include_content = (quoted_string | ((Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress()))
include_expr = (
Keyword("include", caseless=True).suppress() + (
include_content | (
Keyword("required") - Literal('(').suppress() - include_content - Literal(')').suppress()
)
)
).setParseAction(include_config)
root_dict_expr = Forward()
dict_expr = Forward()
list_expr = Forward()
multi_value_expr = ZeroOrMore(comment_eol | include_expr | substitution_expr | dict_expr | list_expr | value_expr | (Literal(
'\\') - eol).suppress())
# for a dictionary : or = is optional
# last zeroOrMore is because we can have t = {a:4} {b: 6} {c: 7} which is dictionary concatenation
inside_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma))
inside_root_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma), root=True)
dict_expr << Suppress('{') - inside_dict_expr - Suppress('}')
root_dict_expr << Suppress('{') - inside_root_dict_expr - Suppress('}')
list_entry = ConcatenatedValueParser(multi_value_expr)
list_expr << Suppress('[') - ListParser(list_entry - ZeroOrMore(eol_comma - list_entry)) - Suppress(']')
# special case when we have a value assignment where the string can potentially be the remainder of the line
assign_expr << Group(
key - ZeroOrMore(comment_no_comma_eol) - (dict_expr | (Literal('=') | Literal(':') | Literal('+=')) - ZeroOrMore(
comment_no_comma_eol) - ConcatenatedValueParser(multi_value_expr))
)
# the file can be { ... } where {} can be omitted or []
config_expr = ZeroOrMore(comment_eol | eol) + (list_expr | root_dict_expr | inside_root_dict_expr) + ZeroOrMore(
comment_eol | eol_comma)
config = config_expr.parseString(content, parseAll=True)[0]
if resolve:
allow_unresolved = resolve and unresolved_value is not DEFAULT_SUBSTITUTION and unresolved_value is not MANDATORY_SUBSTITUTION
has_unresolved = cls.resolve_substitutions(config, allow_unresolved)
if has_unresolved and unresolved_value is MANDATORY_SUBSTITUTION:
raise ConfigSubstitutionException('resolve cannot be set to True and unresolved_value to MANDATORY_SUBSTITUTION')
if unresolved_value is not NO_SUBSTITUTION and unresolved_value is not DEFAULT_SUBSTITUTION:
cls.unresolve_substitutions_to_value(config, unresolved_value)
return config
示例8: split
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def split(s):
if s is None or "!" in s:
return []
match = ZeroOrMore(Group(Word(alphas+"æøåÆØÅ") + Regex(r"[0-9/ ]*\d")))
result = match.parseString(s.replace("%", ""))
return result.asList()
示例9: Word
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
#
# A simple example showing the use of the implied listAllMatches=True for
# results names with a trailing '*' character.
#
# This example performs work similar to itertools.groupby, but without
# having to sort the input first.
#
from pyparsing import Word, ZeroOrMore, nums
aExpr = Word("A", nums)
bExpr = Word("B", nums)
cExpr = Word("C", nums)
grammar = ZeroOrMore(aExpr("A*") | bExpr("B*") | cExpr("C*"))
results = grammar.parseString("A1 B1 A2 C1 B2 A3")
print results.dump()
示例10: bs
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
param.setParseAction(paramfun)
def bs(c): return Literal("\\" + c)
singles = bs("[") | bs("]") | bs("{") | bs("}") | bs("\\") | bs("&") | bs("_") | bs(",") | bs("#") | bs("\n") | bs(";") | bs("|") | bs("%") | bs("*") | bs("~") | bs("^")
texcmd << (singles | Word("\\", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", min = 2)) + ZeroOrMoreAsList(arg) + ZeroOrMoreAsList(param)
def texcmdfun(s, loc, toks):
return TexCmd(s, loc, toks)
texcmd.setParseAction(texcmdfun)
#legal = "".join([chr(x) for x in set(range(32, 127)) - set(backslash)])
#filler = Word(legal)
document = ZeroOrMore(dollarmath | texcmd | filler) + StringEnd().suppress()
if 0:
s = "This is \\\\ test"
print s
for t in document.parseString(s):
if isinstance(t, TexCmd):
print '====> cmd=[%s]' % t.cmd, t
else:
print '====>', t
sys.exit(-1)
selfstr = open( __file__).read() # Own source as a string. Used as part of hash.
hashbase = hashlib.md5(selfstr)
def tokenize(filename):
f = open(filename, "rt")
def uncomment(s):
if '%' in s and not '\\%' in s:
return s[:s.index('%')] + '\n'
示例11: parse_actions
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
def parse_actions(actions):
action = p4_action()
all_actions = ZeroOrMore(action)
return all_actions.parseString(actions)
示例12: SFZParser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
class SFZParser(object):
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)
def handle_include(self, s, loc, toks):
path = os.path.join(self.base_path, normalize_path(toks[0].value))
try:
with open(path) as fp:
f = fp.read()
except IOError as exc:
raise IncludeException(
s, loc=toks[0].locn_start, msg=str(exc))
subparser = SFZParser(path, f, self.state)
subparser.sfz_file.parseString(f)
def handle_section(self, s, loc, toks):
name = toks[0]
if name == 'region':
section = Region(self.state.instr, name, group=self.state.current_group, control=self.state.current_control)
self.state.instr.regions.append(section)
elif name == 'group':
section = Section(self.state.instr, name)
self.state.current_group = section
elif name == 'control':
section = Section(self.state.instr, name)
self.state.current_control = section
else:
raise InvalidSectionException(
s, loc, "Invalid section name '%s'" % name)
self.state.current_section = section
def handle_opcode(self, s, loc, toks):
loc = toks[0].locn_start
name = toks[0].value
try:
opdef = opmap[name]
except KeyError:
raise UnknownOpCodeException(
s, loc=loc, msg="Unknown opcode '%s'" % key)
try:
value = opdef.parse_value(toks[1])
except ValueError as exc:
raise InvalidValueException(
s, loc=loc,
msg="Invalid value for opcode '%s': %s" % (key, str(exc)))
self.state.current_section._opcodes[name] = value
self.state.current_section._opcode_locs[name] = (s, loc)
def parse(self):
self.state = ParserState()
self.state.instr = Instrument(os.path.abspath(self.path))
self.sfz_file.parseString(self.text)
for region in self.state.instr.regions:
if not os.path.isfile(region.sample):
s, loc = region.get_opcode_loc('sample')
raise SampleMissingException(
s, loc, "Missing sample '%s'" % region.sample)
return self.state.instr
示例13: ZeroOrMore
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
option << (options_definition + ZeroOrMore(indentedBlock(response, indentStack, True))).setParseAction(Option)
dialog_begin = Literal('begin').suppress() + Group(atom + Optional(Literal('extends').suppress() + atom))
dialog_end = Literal('end').suppress()
dialog = (dialog_begin + ZeroOrMore(indentedBlock(response, indentStack, True)) + dialog_end).setParseAction(Dialog)
dialogs = ZeroOrMore(indentedBlock(dialog, indentStack, False))
if __name__ == '__main__':
print expression.parseString("1 * 2.5 * 8 * (9 + 3.12 - 1 + 4) / |(2 - -(7 - 9))")
print dialogs.parseString("""begin testDialog
Hello, this is a greating response!
if player:health > 10 then
~ This is option A
~ This is option B with a response
Option B Response
~ Yes
~ No, send event
-> player!test,
-> self!test2
Another possible initial response.
~ Alt Option 1
~ Alt Option 2
end
begin testDialog2 extends testDialog
end
""")
示例14: Parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
#.........这里部分代码省略.........
self.end_for = Literal('}')
self.end_for.setParseAction(self.AST.end_for)
self.for_loop << Group(self.for_ + ~White() + Suppress(self.for_init) +
Optional(delimitedList(self.decl ^ self.id_set))("init") + Suppress(self.for_terminator) +
Optional(self.terminator_expr) + Suppress(self.for_increment) +
Optional(delimitedList(self.id_set))("increm") + Suppress(self.r_bracket) +
Suppress(self.for_body) + self.stmt("loop_body") + Suppress(self.end_for))
self.if_condition = Suppress(self.l_bracket) + self.expr + Suppress(self.r_bracket)
self.if_condition.setParseAction(self.AST.if_cond)
self.if_.setParseAction(self.AST.begin_if)
self.if_body_st = Literal('{')
self.if_body_st.setParseAction(self.AST.if_body_st)
self.if_body_end = Literal('}')
self.if_body_end.setParseAction(self.AST.if_body_end)
self.if_stmt = Group(self.if_ + self.if_condition("if_cond") + Suppress(self.if_body_st) + Group(self.stmt).setResultsName("body") + Suppress(self.if_body_end))
self.single_expr = self.expr + Suppress(self.term_st)
self.single_expr.setParseAction(self.AST.stand_alone_expr)
self.stmt << ZeroOrMore(self.decl + Suppress(self.term_st)
^ self.function_decl
^ self.id_set + Suppress(self.term_st)
^ self.single_expr
^ self.for_loop
^ self.if_stmt
^ self.return_stmt + Suppress(self.term_st)
^ self.sbox_call + Suppress(self.term_st))
self.grammar_test = self.stmt + StringEnd() # Allows single statements to be parsed
self.grammar = ZeroOrMore(self.function_decl
^ self.seq_decl + Suppress(self.term_st)) + StringEnd()
def nest_operand_pairs(self, tokens):
tokens = tokens[0]
ret = ParseResults(tokens[:3])
remaining = iter(tokens[3:])
done = False
while not done:
next_pair = (next(remaining, None), next(remaining, None))
if next_pair == (None, None):
done = True
break
ret = ParseResults([ret])
ret += ParseResults(list(next_pair))
return [ret]
@property
def AST(self):
return self._AST
@AST.setter
def AST(self, value):
self._AST = value
def analyse_tree_test(self, AST):
return self.semantic_analyser.analyse(AST)
def parse_test_unit(self, data_in):
"""Parses single statements"""
try:
res = self.grammar_test.parseString(data_in)
except ParseException as details:
print("The following error occured:")
print(details)
return False
if type(res[0]) is not bool:
pass
# print(res[0].dump())
return [res, True]
def parse_test_AST_semantic(self, data_in):
"""Parses single statements and returns AST"""
try:
self.grammar_test.parseString(data_in)
except ParseException as details:
print("The following error occured:")
print(details)
return False
return self.AST
def parse_test_integration(self, data_in):
"""Only Parses Statements in functions"""
try:
res = self.grammar.parseString(data_in)
except ParseException as details:
print("The following error occured:")
print(details)
return False
# if type(res[0]) is not bool:
# print(res[0].dump())
return [res, True]
def parse(self, data_in):
"""Prod parsing entry point"""
self.grammar.parseString(data_in)
if self.semantic_analyser.analyse(self.AST, True) is True:
return self.semantic_analyser.IR.translate()
示例15: len
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import parseString [as 别名]
start = site_contents.find(' ', site_contents.find('Current Cutout Values:'))
end = site_contents.find('\r\n', start)
cutout = site_contents[start:end].strip().split(' ')
cutout = [p for p in cutout if len(p) != 0]
primal_grammar = OneOrMore(Combine(Literal('Primal') + ' ' + Word(alphas)) + Word(nums+'.') * 2)
start = site_contents.find('Primal Rib')
end = site_contents.find('---', start)
primal = primal_grammar.parseString(site_contents[start:end])
primal = [primal[i:i+3] for i in range(0, len(primal), 3)]
start = site_contents.find('Choice Cuts', start)
end = site_contents.find('---', start)
volume_grammar = ZeroOrMore(Combine(Word(alphas) + ' ' + ZeroOrMore(Word(alphas))) + (Word(nums + '.' + ',' ) + Suppress(Word(alphas))) * 2)
volume = volume_grammar.parseString(site_contents[start:end])
volume = [volume[i:i + 3] for i in range(0, len(volume), 3)]
choice = []
select = []
choice_select = []
ground_beef = []
blended_gb = []
beef_trimmings = []
end1 = site_contents.find('Rib,', end)-10
end2 = site_contents.find('Rib,', site_contents.find('-----', end1))-10
end3 = site_contents.find('Rib,', site_contents.find('-----', end2))-10
end4 = site_contents.find('Ground Beef 73%', end3)
end5 = site_contents.find('Blended Ground Beef', end4)
end6 = site_contents.find('Fresh 50%', end5)
end = [end1, end2, end3, end4, end5, end6]