![]() |
Qucs-S S-parameter Viewer & RF Synthesis Tools
|


Classes | |
| class | _CacheType |
| class | DebugActions |
Public Member Functions | |
| using_each (cls, seq, **class_kwargs) | |
| __init__ (self, bool savelist=False) | |
| "ParserElement" | suppress_warning (self, Diagnostics warning_type) |
| visit_all (self) | |
| "ParserElement" | copy (self) |
| "ParserElement" | set_results_name (self, str name, bool list_all_matches=False, *bool listAllMatches=False) |
| "ParserElement" | set_break (self, bool break_flag=True) |
| "ParserElement" | set_parse_action (self, *ParseAction fns, **kwargs) |
| "ParserElement" | add_parse_action (self, *ParseAction fns, **kwargs) |
| "ParserElement" | add_condition (self, *ParseCondition fns, **kwargs) |
| "ParserElement" | set_fail_action (self, ParseFailAction fn) |
| int | preParse (self, str instring, int loc) |
| parseImpl (self, instring, loc, doActions=True) | |
| postParse (self, instring, loc, tokenlist) | |
| int | try_parse (self, str instring, int loc, *bool raise_fatal=False, bool do_actions=False) |
| bool | can_parse_next (self, str instring, int loc, bool do_actions=False) |
| ParseResults | parse_string (self, str instring, bool parse_all=False, *bool parseAll=False) |
| Generator[Tuple[ParseResults, int, int], None, None] | scan_string (self, str instring, int max_matches=_MAX_INT, bool overlap=False, *bool debug=False, int maxMatches=_MAX_INT) |
| str | transform_string (self, str instring, *bool debug=False) |
| ParseResults | search_string (self, str instring, int max_matches=_MAX_INT, *bool debug=False, int maxMatches=_MAX_INT) |
| Generator[str, None, None] | split (self, str instring, int maxsplit=_MAX_INT, bool include_separators=False, *includeSeparators=False) |
| "ParserElement" | __add__ (self, other) |
| "ParserElement" | __radd__ (self, other) |
| "ParserElement" | __sub__ (self, other) |
| "ParserElement" | __rsub__ (self, other) |
| "ParserElement" | __mul__ (self, other) |
| "ParserElement" | __rmul__ (self, other) |
| "ParserElement" | __or__ (self, other) |
| "ParserElement" | __ror__ (self, other) |
| "ParserElement" | __xor__ (self, other) |
| "ParserElement" | __rxor__ (self, other) |
| "ParserElement" | __and__ (self, other) |
| "ParserElement" | __rand__ (self, other) |
| "ParserElement" | __invert__ (self) |
| __getitem__ (self, key) | |
| "ParserElement" | __call__ (self, typing.Optional[str] name=None) |
| "ParserElement" | suppress (self) |
| "ParserElement" | ignore_whitespace (self, bool recursive=True) |
| "ParserElement" | leave_whitespace (self, bool recursive=True) |
| "ParserElement" | set_whitespace_chars (self, Union[Set[str], str] chars, bool copy_defaults=False) |
| "ParserElement" | parse_with_tabs (self) |
| "ParserElement" | ignore (self, "ParserElement" other) |
| "ParserElement" | set_debug_actions (self, DebugStartAction start_action, DebugSuccessAction success_action, DebugExceptionAction exception_action) |
| "ParserElement" | set_debug (self, bool flag=True, bool recurse=False) |
| str | default_name (self) |
| "ParserElement" | set_name (self, str name) |
| str | name (self) |
| str | __str__ (self) |
| str | __repr__ (self) |
| "ParserElement" | streamline (self) |
| List["ParserElement"] | recurse (self) |
| None | validate (self, validateTrace=None) |
| ParseResults | parse_file (self, Union[str, Path, TextIO] file_or_filename, str encoding="utf-8", bool parse_all=False, *bool parseAll=False) |
| __eq__ (self, other) | |
| __hash__ (self) | |
| bool | matches (self, str test_string, bool parse_all=True, *bool parseAll=True) |
| Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]] | run_tests (self, Union[str, List[str]] tests, bool parse_all=True, typing.Optional[Union["ParserElement", str]] comment="#", bool full_dump=True, bool print_results=True, bool failure_tests=False, typing.Optional[Callable[[str, ParseResults], str]] post_parse=None, typing.Optional[TextIO] file=None, bool with_line_numbers=False, *bool parseAll=True, bool fullDump=True, bool printResults=True, bool failureTests=False, typing.Optional[Callable[[str, ParseResults], str]] postParse=None) |
| None | create_diagram (self, Union[TextIO, Path, str] output_html, int vertical=3, bool show_results_names=False, bool show_groups=False, bool embed=False, **kwargs) |
| setResultsName (self) | |
| setBreak (self) | |
| setParseAction (self) | |
| addParseAction (self) | |
| addCondition (self) | |
| setFailAction (self) | |
| tryParse (self) | |
| parseString (self) | |
| scanString (self) | |
| transformString (self) | |
| searchString (self) | |
| ignoreWhitespace (self) | |
| leaveWhitespace (self) | |
| setWhitespaceChars (self) | |
| parseWithTabs (self) | |
| setDebugActions (self) | |
| setDebug (self) | |
| setName (self) | |
| parseFile (self) | |
| runTests (self) | |
Static Public Member Functions | |
| None | set_default_whitespace_chars (str chars) |
| None | inline_literals_using (type cls) |
| None | reset_cache () |
| None | disable_memoization () |
| None | enable_left_recursion (typing.Optional[int] cache_size_limit=None, *force=False) |
| None | enable_packrat (int cache_size_limit=128, *bool force=False) |
| inlineLiteralsUsing () | |
| setDefaultWhitespaceChars () | |
| enableLeftRecursion () | |
| enablePackrat () | |
Static Public Attributes | |
| str | DEFAULT_WHITE_CHARS = " \n\t\r" |
| bool | verbose_stacktrace = False |
| recursion_lock = RLock() | |
| dict | recursion_memos = {} |
| tuple | packrat_cache |
| packrat_cache_lock = RLock() | |
| list | packrat_cache_stats = [0, 0] |
| bool | canParseNext = can_parse_next |
| None | resetCache = reset_cache |
| str | defaultName = default_name |
Protected Member Functions | |
| _setResultsName (self, name, listAllMatches=False) | |
| int | _skipIgnorables (self, str instring, int loc) |
| Tuple[int, ParseResults] | _parseNoCache (self, instring, loc, doActions=True, callPreParse=True) |
| Tuple[int, ParseResults] | _parseCache (self, instring, loc, doActions=True, callPreParse=True) |
| str | _generateDefaultName (self) |
| _checkRecursion (self, parseElementList) | |
Protected Attributes | |
| _parse | |
| _defaultName | |
Static Protected Attributes | |
| type | _literalStringClass = None |
| Tuple[int, ParseResults] | _parse = _parseNoCache |
| bool | _packratEnabled = False |
| bool | _left_recursion_enabled = False |
Abstract base level parser element class.
| pip._vendor.pyparsing.core.ParserElement.__init__ | ( | self, | |
| bool | savelist = False |
||
| ) |
Reimplemented in pip._vendor.pyparsing.core.Regex, and pip._vendor.pyparsing.core.DelimitedList.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__add__ | ( | self, | |
| other | |||
| ) |
Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`
converts them to :class:`Literal`\\ s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print(hello, "->", greet.parse_string(hello))
prints::
Hello, World! -> ['Hello', ',', 'World', '!']
``...`` may be used as a parse expression as a short form of :class:`SkipTo`::
Literal('start') + ... + Literal('end')
is equivalent to::
Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
Note that the skipped text is returned with '_skipped' as a results name,
and to support having multiple skips in the same parser, the value returned is
a list of all skipped text.
Reimplemented in pip._vendor.pyparsing.core._PendingSkip, and pip._vendor.pyparsing.core.Suppress.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__and__ | ( | self, | |
| other | |||
| ) |
Implementation of ``&`` operator - returns :class:`Each`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__call__ | ( | self, | |
| typing.Optional[str] | name = None |
||
| ) |
Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.
If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be
passed as ``True``.
If ``name`` is omitted, same as calling :class:`copy`.
Example::
# these are equivalent
userdata = Word(alphas).set_results_name("name") + Word(nums + "-").set_results_name("socsecno")
userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
| pip._vendor.pyparsing.core.ParserElement.__getitem__ | ( | self, | |
| key | |||
| ) |
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr[..., n]`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
``None`` may be used in place of ``...``.
Note that ``expr[..., n]`` and ``expr[m, n]`` do not raise an exception
if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is
desired, then write ``expr[..., n] + ~expr``.
For repetition with a stop_on expression, use slice notation:
- ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)``
- ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)``
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__invert__ | ( | self | ) |
Implementation of ``~`` operator - returns :class:`NotAny`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__mul__ | ( | self, | |
| other | |||
| ) |
Implementation of ``*`` operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also be multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
Note that ``expr*(None, n)`` does not raise an exception if
more than n exprs exist in the input stream; that is,
``expr*(None, n)`` does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
``expr*(None, n) + ~expr``
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__or__ | ( | self, | |
| other | |||
| ) |
Implementation of ``|`` operator - returns :class:`MatchFirst`
Reimplemented in pip._vendor.pyparsing.core.Forward.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__radd__ | ( | self, | |
| other | |||
| ) |
Implementation of ``+`` operator when left operand is not a :class:`ParserElement`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__rand__ | ( | self, | |
| other | |||
| ) |
Implementation of ``&`` operator when left operand is not a :class:`ParserElement`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__ror__ | ( | self, | |
| other | |||
| ) |
Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__rsub__ | ( | self, | |
| other | |||
| ) |
Implementation of ``-`` operator when left operand is not a :class:`ParserElement`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__rxor__ | ( | self, | |
| other | |||
| ) |
Implementation of ``^`` operator when left operand is not a :class:`ParserElement`
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__sub__ | ( | self, | |
| other | |||
| ) |
Implementation of ``-`` operator, returns :class:`And` with error stop
Reimplemented in pip._vendor.pyparsing.core.Suppress.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.__xor__ | ( | self, | |
| other | |||
| ) |
Implementation of ``^`` operator - returns :class:`Or`
|
protected |
Child classes must define this method, which defines how the ``default_name`` is set.
Reimplemented in pip._vendor.pyparsing.core._PendingSkip, pip._vendor.pyparsing.core.Token, pip._vendor.pyparsing.core.Literal, pip._vendor.pyparsing.core.Empty, pip._vendor.pyparsing.core.Keyword, pip._vendor.pyparsing.core.CloseMatch, pip._vendor.pyparsing.core.Word, pip._vendor.pyparsing.core.Regex, pip._vendor.pyparsing.core.QuotedString, pip._vendor.pyparsing.core.CharsNotIn, pip._vendor.pyparsing.core.White, pip._vendor.pyparsing.core.ParseExpression, pip._vendor.pyparsing.core.And._ErrorStop, pip._vendor.pyparsing.core.And, pip._vendor.pyparsing.core.Or, pip._vendor.pyparsing.core.MatchFirst, pip._vendor.pyparsing.core.Each, pip._vendor.pyparsing.core.ParseElementEnhance, pip._vendor.pyparsing.core.NotAny, pip._vendor.pyparsing.core.OneOrMore, pip._vendor.pyparsing.core.ZeroOrMore, pip._vendor.pyparsing.core.DelimitedList, pip._vendor.pyparsing.core.Opt, and pip._vendor.pyparsing.core.Forward.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.add_condition | ( | self, | |
| *ParseCondition | fns, | ||
| ** | kwargs | ||
| ) |
Add a boolean predicate function to expression's list of parse actions. See
:class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,
functions passed to ``add_condition`` need to return boolean success/fail of the condition.
Optional keyword arguments:
- ``message`` = define a custom message to be used in the raised exception
- ``fatal`` = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise
ParseException
- ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls,
default=False
Example::
integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0),
(line:1, col:1)
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.add_parse_action | ( | self, | |
| *ParseAction | fns, | ||
| ** | kwargs | ||
| ) |
Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. See examples in :class:`copy`.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.copy | ( | self | ) |
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress("K")
integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
print((integerK | integerM | integer)[1, ...].parse_string("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of ``expr.copy()`` is just ``expr()``::
integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
Reimplemented in pip._vendor.pyparsing.core.ParseExpression, and pip._vendor.pyparsing.core.Forward.
| None pip._vendor.pyparsing.core.ParserElement.create_diagram | ( | self, | |
| Union[TextIO, Path, str] | output_html, | ||
| int | vertical = 3, |
||
| bool | show_results_names = False, |
||
| bool | show_groups = False, |
||
| bool | embed = False, |
||
| ** | kwargs | ||
| ) |
Create a railroad diagram for the parser. Parameters: - ``output_html`` (str or file-like object) - output target for generated diagram HTML - ``vertical`` (int) - threshold for formatting multiple alternatives vertically instead of horizontally (default=3) - ``show_results_names`` - bool flag whether diagram should show annotations for defined results names - ``show_groups`` - bool flag whether groups should be highlighted with an unlabeled surrounding box - ``embed`` - bool flag whether generated HTML should omit <HEAD>, <BODY>, and <DOCTYPE> tags to embed the resulting HTML in an enclosing HTML source - ``head`` - str containing additional HTML to insert into the <HEAD> section of the generated code; can be used to insert custom CSS styling - ``body`` - str containing additional HTML to insert at the beginning of the <BODY> section of the generated code Additional diagram-formatting keyword arguments can also be included; see railroad.Diagram class.
|
static |
Disables active Packrat or Left Recursion parsing and their memoization This method also works if neither Packrat nor Left Recursion are enabled. This makes it safe to call before activating Packrat nor Left Recursion to clear any previous settings.
|
static |
Enables "bounded recursion" parsing, which allows for both direct and indirect
left-recursion. During parsing, left-recursive :class:`Forward` elements are
repeatedly matched with a fixed recursion depth that is gradually increased
until finding the longest match.
Example::
from pip._vendor import pyparsing as pp
pp.ParserElement.enable_left_recursion()
E = pp.Forward("E")
num = pp.Word(pp.nums)
# match `num`, or `num '+' num`, or `num '+' num '+' num`, ...
E <<= E + '+' - num | num
print(E.parse_string("1+2+3"))
Recursion search naturally memoizes matches of ``Forward`` elements and may
thus skip reevaluation of parse actions during backtracking. This may break
programs with parse actions which rely on strict ordering of side-effects.
Parameters:
- ``cache_size_limit`` - (default=``None``) - memoize at most this many
``Forward`` elements during matching; if ``None`` (the default),
memoize all ``Forward`` elements.
Bounded Recursion parsing works similar but not identical to Packrat parsing,
thus the two cannot be used together. Use ``force=True`` to disable any
previous, conflicting settings.
|
static |
Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- ``cache_size_limit`` - (default= ``128``) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method :class:`ParserElement.enable_packrat`.
For best results, call ``enable_packrat()`` immediately after
importing pyparsing.
Example::
from pip._vendor import pyparsing
pyparsing.ParserElement.enable_packrat()
Packrat parsing works similar but not identical to Bounded Recursion parsing,
thus the two cannot be used together. Use ``force=True`` to disable any
previous, conflicting settings.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.ignore | ( | self, | |
| "ParserElement" | other | ||
| ) |
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = Word(alphas)[1, ...]
patt.parse_string('ablaj /* comment */ lskjd')
# -> ['ablaj']
patt.ignore(c_style_comment)
patt.parse_string('ablaj /* comment */ lskjd')
# -> ['ablaj', 'lskjd']
Reimplemented in pip._vendor.pyparsing.core.ParseExpression, pip._vendor.pyparsing.core.ParseElementEnhance, and pip._vendor.pyparsing.core.Combine.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.ignore_whitespace | ( | self, | |
| bool | recursive = True |
||
| ) |
Enables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)
Reimplemented in pip._vendor.pyparsing.core.ParseExpression, pip._vendor.pyparsing.core.ParseElementEnhance, and pip._vendor.pyparsing.core.Forward.
|
static |
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parse_string("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inline_literals_using(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parse_string("1999/12/31") # -> ['1999', '12', '31']
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.leave_whitespace | ( | self, | |
| bool | recursive = True |
||
| ) |
Disables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)
Reimplemented in pip._vendor.pyparsing.core.ParseExpression, pip._vendor.pyparsing.core.ParseElementEnhance, and pip._vendor.pyparsing.core.Forward.
| bool pip._vendor.pyparsing.core.ParserElement.matches | ( | self, | |
| str | test_string, | ||
| bool | parse_all = True, |
||
| *bool | parseAll = True |
||
| ) |
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- ``test_string`` - to test against this expression for a match
- ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
| ParseResults pip._vendor.pyparsing.core.ParserElement.parse_file | ( | self, | |
| Union[str, Path, TextIO] | file_or_filename, | ||
| str | encoding = "utf-8", |
||
| bool | parse_all = False, |
||
| *bool | parseAll = False |
||
| ) |
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
| ParseResults pip._vendor.pyparsing.core.ParserElement.parse_string | ( | self, | |
| str | instring, | ||
| bool | parse_all = False, |
||
| *bool | parseAll = False |
||
| ) |
Parse a string with respect to the parser definition. This function is intended as the primary interface to the
client code.
:param instring: The input string to be parsed.
:param parse_all: If set, the entire input string must match the grammar.
:param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.
:raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.
:returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or
an object with attributes if the given parser includes results names.
If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This
is also equivalent to ending the grammar with :class:`StringEnd`\\ ().
To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are
converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string
contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string
being parsed, one can ensure a consistent view of the input string by doing one of the following:
- calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),
- define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the
parse action's ``s`` argument, or
- explicitly expand the tabs in your input string before calling ``parse_string``.
Examples:
By default, partial matches are OK.
>>> res = Word('a').parse_string('aaaaabaaa')
>>> print(res)
['aaaaa']
The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children
directly to see more examples.
It raises an exception if parse_all flag is set and instring does not match the whole grammar.
>>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)
Traceback (most recent call last):
...
pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6)
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.parse_with_tabs | ( | self | ) |
Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string. Must be called before ``parse_string`` when the input grammar contains elements that match ``<TAB>`` characters.
| Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]] pip._vendor.pyparsing.core.ParserElement.run_tests | ( | self, | |
| Union[str, List[str]] | tests, | ||
| bool | parse_all = True, |
||
| typing.Optional[Union["ParserElement", str]] | comment = "#", |
||
| bool | full_dump = True, |
||
| bool | print_results = True, |
||
| bool | failure_tests = False, |
||
| typing.Optional[Callable[[str, ParseResults], str]] | post_parse = None, |
||
| typing.Optional[TextIO] | file = None, |
||
| bool | with_line_numbers = False, |
||
| *bool | parseAll = True, |
||
| bool | fullDump = True, |
||
| bool | printResults = True, |
||
| bool | failureTests = False, |
||
| typing.Optional[Callable[[str, ParseResults], str]] | postParse = None |
||
| ) |
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- ``tests`` - a list of separate test strings, or a multiline string of test strings
- ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
- ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- ``print_results`` - (default= ``True``) prints test output to stdout
- ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing
- ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as
`fn(test_string, parse_results)` and returns a string to be added to the test output
- ``file`` - (default= ``None``) optional file-like object to which test output will be written;
if None, will default to ``sys.stdout``
- ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if ``failure_tests`` is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.run_tests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.run_tests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failure_tests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading ``'r'``.)
| Generator[Tuple[ParseResults, int, int], None, None] pip._vendor.pyparsing.core.ParserElement.scan_string | ( | self, | |
| str | instring, | ||
| int | max_matches = _MAX_INT, |
||
| bool | overlap = False, |
||
| *bool | debug = False, |
||
| int | maxMatches = _MAX_INT |
||
| ) |
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``max_matches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See :class:`parse_string` for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens, start, end in Word(alphas).scan_string(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
| ParseResults pip._vendor.pyparsing.core.ParserElement.search_string | ( | self, | |
| str | instring, | ||
| int | max_matches = _MAX_INT, |
||
| *bool | debug = False, |
||
| int | maxMatches = _MAX_INT |
||
| ) |
Another extension to :class:`scan_string`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``max_matches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity"))
# the sum() builtin can be used to merge results into a single ParseResults object
print(sum(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity")))
prints::
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_break | ( | self, | |
| bool | break_flag = True |
||
| ) |
Method to invoke the Python pdb debugger when this element is about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to disable.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_debug | ( | self, | |
| bool | flag = True, |
||
| bool | recurse = False |
||
| ) |
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to ``True`` to enable, ``False`` to disable.
Set ``recurse`` to ``True`` to set the debug flag on this expression and all sub-expressions.
Example::
wd = Word(alphas).set_name("alphaword")
integer = Word(nums).set_name("numword")
term = wd | integer
# turn on debugging for wd
wd.set_debug()
term[1, ...].parse_string("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`set_debug_actions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``set_name`` is ``"W:(A-Za-z)"``.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_debug_actions | ( | self, | |
| DebugStartAction | start_action, | ||
| DebugSuccessAction | success_action, | ||
| DebugExceptionAction | exception_action | ||
| ) |
Customize display of debugging messages while doing pattern matching: - ``start_action`` - method to be called when an expression is about to be parsed; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)`` - ``success_action`` - method to be called when an expression has successfully parsed; should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)`` - ``exception_action`` - method to be called when expression fails to parse; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``
|
static |
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.set_default_whitespace_chars(" \t")
Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def']
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_fail_action | ( | self, | |
| ParseFailAction | fn | ||
| ) |
Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - ``s`` = string being parsed - ``loc`` = location where expression match was attempted and failed - ``expr`` = the parse expression that failed - ``err`` = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_name | ( | self, | |
| str | name | ||
| ) |
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parse_string("ABC") # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)
Word(nums).set_name("integer").parse_string("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_parse_action | ( | self, | |
| *ParseAction | fns, | ||
| ** | kwargs | ||
| ) |
Define one or more actions to perform when successfully matching parse element definition.
Parse actions can be called to perform data conversions, do extra validation,
update external data structures, or enhance or replace the parsed tokens.
Each parse action ``fn`` is a callable method with 0-3 arguments, called as
``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
- ``s`` = the original string being parsed (see note below)
- ``loc`` = the location of the matching substring
- ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object
The parsed tokens are passed to the parse action as ParseResults. They can be
modified in place using list-style append, extend, and pop operations to update
the parsed list elements; and with dictionary-style item set and del operations
to add, update, or remove any named results. If the tokens are modified in place,
it is not necessary to return them with a return statement.
Parse actions can also completely replace the given tokens, with another ``ParseResults``
object, or with some entirely different object (common for parse actions that perform data
conversions). A convenient way to build a new parse result is to define the values
using a dict, and then create the return value using :class:`ParseResults.from_dict`.
If None is passed as the ``fn`` parse action, all previously added parse actions for this
expression are cleared.
Optional keyword arguments:
- ``call_during_try`` = (default= ``False``) indicate if parse action should be run during
lookaheads and alternate testing. For parse actions that have side effects, it is
important to only call the parse action once it is determined that it is being
called as part of a successful parse. For parse actions that perform additional
validation, then call_during_try should be passed as True, so that the validation
code is included in the preliminary "try" parses.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`parse_string` for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
Example::
# parse dates in the form YYYY/MM/DD
# use parse action to convert toks from str to int at parse time
def convert_to_int(toks):
return int(toks[0])
# use a parse action to verify that the date is a valid date
def is_valid_date(instring, loc, toks):
from datetime import date
year, month, day = toks[::2]
try:
date(year, month, day)
except ValueError:
raise ParseException(instring, loc, "invalid date given")
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
# add parse actions
integer.set_parse_action(convert_to_int)
date_str.set_parse_action(is_valid_date)
# note that integer fields are now ints, not strings
date_str.run_tests('''
# successful parse - note that integer fields were converted to ints
1999/12/31
# fail - invalid date
1999/13/31
''')
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_results_name | ( | self, | |
| str | name, | ||
| bool | list_all_matches = False, |
||
| *bool | listAllMatches = False |
||
| ) |
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
Normally, results names are assigned as you would assign keys in a dict:
any existing value is overwritten by later values. If it is necessary to
keep all values captured for a particular results name, call ``set_results_name``
with ``list_all_matches`` = True.
NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
``expr("name")`` in place of ``expr.set_results_name("name")``
- see :class:`__call__`. If ``list_all_matches`` is required, use
``expr("name*")``.
Example::
date_str = (integer.set_results_name("year") + '/'
+ integer.set_results_name("month") + '/'
+ integer.set_results_name("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.set_whitespace_chars | ( | self, | |
| Union[Set[str], str] | chars, | ||
| bool | copy_defaults = False |
||
| ) |
Overrides the default whitespace chars
| Generator[str, None, None] pip._vendor.pyparsing.core.ParserElement.split | ( | self, | |
| str | instring, | ||
| int | maxsplit = _MAX_INT, |
||
| bool | include_separators = False, |
||
| * | includeSeparators = False |
||
| ) |
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``include_separators`` argument (default= ``False``), if the separating
matching text should be included in the split results.
Example::
punc = one_of(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.suppress | ( | self | ) |
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output.
Reimplemented in pip._vendor.pyparsing.core.Suppress.
| "ParserElement" pip._vendor.pyparsing.core.ParserElement.suppress_warning | ( | self, | |
| Diagnostics | warning_type | ||
| ) |
Suppress warnings emitted for a particular diagnostic on this expression.
Example::
base = pp.Forward()
base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)
# statement would normally raise a warning, but is now suppressed
print(base.parse_string("x"))
| str pip._vendor.pyparsing.core.ParserElement.transform_string | ( | self, | |
| str | instring, | ||
| *bool | debug = False |
||
| ) |
Extension to :class:`scan_string`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transform_string``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transform_string()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transform_string()`` returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.set_parse_action(lambda toks: toks[0].title())
print(wd.transform_string("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
| pip._vendor.pyparsing.core.ParserElement.using_each | ( | cls, | |
| seq, | |||
| ** | class_kwargs | ||
| ) |
Yields a sequence of class(obj, **class_kwargs) for obj in seq.
Example::
LPAR, RPAR, LBRACE, RBRACE, SEMI = Suppress.using_each("(){};")
| None pip._vendor.pyparsing.core.ParserElement.validate | ( | self, | |
validateTrace = None |
|||
| ) |
Check defined expressions for valid structure, check for infinite recursive definitions.
Reimplemented in pip._vendor.pyparsing.core.ParseExpression, pip._vendor.pyparsing.core.ParseElementEnhance, and pip._vendor.pyparsing.core.Forward.
| pip._vendor.pyparsing.core.ParserElement.visit_all | ( | self | ) |
General-purpose method to yield all expressions and sub-expressions in a grammar. Typically just for internal use.
|
static |