Python pyparsing.ParserElement() Examples
The following are 16
code examples of pyparsing.ParserElement().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyparsing
, or try the search function
.
Example #1
Source File: expansions.py From pyjsgf with MIT License | 6 votes |
def _set_matcher_element_attributes(self, element): # Set the ParserElement's action. element.setParseAction(self._parse_action) # Save the element's original postParse function. closure = element.postParse # Set a new function and use the original function for returning values. def postParse(instring, loc, tokenlist): if isinstance(tokenlist, pyparsing.ParseResults): s = " ".join(tokenlist.asList()) elif isinstance(tokenlist, list): s = "".join(tokenlist) elif isinstance(tokenlist, string_types): s = tokenlist else: raise TypeError("postParse received invalid tokenlist %s" % tokenlist) self.matching_slice = slice(loc - len(s), loc) return closure(instring, loc, tokenlist) element.postParse = postParse # Return the element. return element
Example #2
Source File: protein_modification.py From pybel with MIT License | 6 votes |
def get_protein_modification_language(concept_qualified: ParserElement) -> ParserElement: """Build a protein modification parser.""" pmod_concept = MatchFirst([ concept_qualified, pmod_default_ns, pmod_legacy_ns, ]) return pmod_tag + nest( Group(pmod_concept)(CONCEPT) + Optional( WCW + amino_acid(PMOD_CODE) + Optional(WCW + ppc.integer(PMOD_POSITION)), ), )
Example #3
Source File: __init__.py From pyparsing with MIT License | 6 votes |
def to_railroad( element: pyparsing.ParserElement, diagram_kwargs: dict = {}, vertical: Union[int, bool] = 5, ) -> List[NamedDiagram]: """ Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram creation if you want to access the Railroad tree before it is converted to HTML :param diagram_kwargs: kwargs to pass to the Diagram() constructor """ # Convert the whole tree underneath the root lookup = ConverterState(diagram_kwargs=diagram_kwargs) _to_diagram_element(element, lookup=lookup, parent=None, vertical=vertical) root_id = id(element) # Convert the root if it hasn't been already if root_id in lookup.first: lookup.first[root_id].mark_for_extraction(root_id, lookup, force=True) # Now that we're finished, we can convert from intermediate structures into Railroad elements resolved = [resolve_partial(partial) for partial in lookup.diagrams.values()] return sorted(resolved, key=lambda diag: diag.index)
Example #4
Source File: __init__.py From pyparsing with MIT License | 6 votes |
def __init__( self, element: pyparsing.ParserElement, converted: EditablePartial, parent: EditablePartial, number: int, name: str = None, index: Optional[int] = None, ): #: The pyparsing element that this represents self.element = element # type: pyparsing.ParserElement #: The name of the element self.name = name # type: str #: The output Railroad element in an unconverted state self.converted = converted # type: EditablePartial #: The parent Railroad element, which we store so that we can extract this if it's duplicated self.parent = parent # type: EditablePartial #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram self.number = number # type: int #: The index of this inside its parent self.parent_index = index # type: Optional[int] #: If true, we should extract this out into a subdiagram self.extract = False # type: bool #: If true, all of this element's chilren have been filled out self.complete = False # type: bool
Example #5
Source File: expansions.py From pyjsgf with MIT License | 5 votes |
def matcher_element(self): """ Lazily initialised `pyparsing` ``ParserElement`` used to match speech to expansions. It will also set ``current_match`` values. :returns: pyparsing.ParserElement """ if not self._matcher_element: element = self._make_matcher_element() self._matcher_element = element else: element = self._matcher_element return element
Example #6
Source File: baseparser.py From pybel with MIT License | 5 votes |
def __init__(self, language: ParserElement, streamline: bool = False) -> None: """Build a parser wrapper using a PyParsing language. :param language: The PyParsing language to use :param streamline: Should the language be streamlined on instantiation? """ self.language = language #: The parser holds an internal state of the current line self._line_number = 0 if streamline: self.streamline()
Example #7
Source File: fragment.py From pybel with MIT License | 5 votes |
def get_fragment_language() -> ParserElement: """Build a protein fragment parser.""" _fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING) _fragment_value = _fragment_value_inner | And([Suppress('"'), _fragment_value_inner, Suppress('"')]) parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION))) return parser_element
Example #8
Source File: truncation.py From pybel with MIT License | 5 votes |
def get_truncation_language() -> ParserElement: """Build a parser for protein truncations.""" l1 = truncation_tag + nest(amino_acid(AMINO_ACID) + ppc.integer(TRUNCATION_POSITION)) l1.setParseAction(_handle_trunc) l2 = truncation_tag + nest(ppc.integer(TRUNCATION_POSITION)) l2.setParseAction(_handle_trunc_legacy) return l1 | l2
Example #9
Source File: gene_modification.py From pybel with MIT License | 5 votes |
def get_gene_modification_language(concept_qualified: ParserElement) -> ParserElement: """Build a gene modification parser.""" concept = MatchFirst([ concept_qualified, gmod_default_ns, ]) return gmod_tag + nest(Group(concept)(CONCEPT))
Example #10
Source File: protein_substitution.py From pybel with MIT License | 5 votes |
def get_protein_substitution_language() -> ParserElement: """Build a protein substitution parser.""" parser_element = psub_tag + nest( amino_acid(PSUB_REFERENCE), ppc.integer(PSUB_POSITION), amino_acid(PSUB_VARIANT), ) parser_element.setParseAction(_handle_psub) return parser_element
Example #11
Source File: variant.py From pybel with MIT License | 5 votes |
def get_hgvs_language() -> ParserElement: """Build a HGVS :class:`pyparsing.ParseElement`.""" hgvs = (variant_characters | quote)(HGVS) language = variant_tags + nest(hgvs) return language
Example #12
Source File: location.py From pybel with MIT License | 5 votes |
def get_location_language(identifier: ParserElement) -> ParserElement: """Build a location parser.""" return Group(location_tag + nest(identifier))(LOCATION)
Example #13
Source File: __init__.py From pyparsing with MIT License | 5 votes |
def __init__(self, diagram_kwargs: dict = {}): #: A dictionary mapping ParserElement IDs to state relating to them self.first = {} # type: Dict[int, ElementState] #: A dictionary mapping ParserElement IDs to subdiagrams generated from them self.diagrams = {} # type: Dict[int, EditablePartial[NamedDiagram]] #: The index of the next unnamed element self.unnamed_index = 1 # type: int #: The index of the next element. This is used for sorting self.index = 0 # type: int #: Shared kwargs that are used to customize the construction of diagrams self.diagram_kwargs = diagram_kwargs # type: dict
Example #14
Source File: __init__.py From pyparsing with MIT License | 5 votes |
def _worth_extracting(element: pyparsing.ParserElement) -> bool: """ Returns true if this element is worth having its own sub-diagram. Simply, if any of its children themselves have children, then its complex enough to extract """ children = element.recurse() return any( [hasattr(child, "expr") or hasattr(child, "exprs") for child in children] )
Example #15
Source File: strategies.py From requirementslib with MIT License | 5 votes |
def flatten_pyparsing_exprs(expr): exprs = set() for child in expr.exprs: if isinstance(child, (Literal, six.string_types)): exprs.add(str(child).strip('"')) elif isinstance(child, (MatchFirst, ParseExpression, ParserElement)): exprs.update(flatten_pyparsing_exprs(child)) return exprs
Example #16
Source File: specs_matcher.py From oslo.utils with Apache License 2.0 | 5 votes |
def match(cmp_value, spec): """Match a given value to a given spec DSL. This uses the grammar defined by make_grammar() :param cmp_value: Value to be checked for match. :param spec: The comparison specification string, for example ``">= 70"`` or ``"s== string_value"``. See ``make_grammar()`` for examples of a specification string. :returns: True if cmp_value is a match for spec. False otherwise. """ expr = make_grammar() try: # As of 2018-01-29 documentation on parseString() # https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#parseString # # parseString() will take our specification string, for example "< 6" # and convert it into a list of ['<', "6"] tree = expr.parseString(spec) except pyparsing.ParseException: # If an exception then we will just check if the value matches the spec tree = [spec] if len(tree) == 1: return tree[0] == cmp_value # tree[0] will contain a string representation of a comparison operation # such as '>=', we then convert that string to a comparison function compare_func = op_methods[tree[0]] return compare_func(cmp_value, *tree[1:])