Skip to content

Instantly share code, notes, and snippets.

@spookylukey
Created September 27, 2017 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spookylukey/591aa8a6a9af7cf0f1e22129b29288d6 to your computer and use it in GitHub Desktop.
Save spookylukey/591aa8a6a9af7cf0f1e22129b29288d6 to your computer and use it in GitHub Desktop.
Hollerith constant parsing in pyparsing
import pyparsing as pp
def hollerith():
intExpr = pp.Word(pp.nums).setParseAction(lambda t: int(t[0]))
stringExpr = pp.Forward()
def countedParseAction(toks):
n = toks[0]
contents = pp.CharsNotIn('', exact=n)
stringExpr << (pp.Suppress(pp.CaselessLiteral('H')) + contents)
return None
intExpr.addParseAction(countedParseAction)
return (pp.Suppress(intExpr) + stringExpr)
@spookylukey
Copy link
Author

Using parsy:

from parsy import generate, regex, string, any_char

@generate
def hollerith():
    num = yield regex(r'[0-9]+').map(int)
    yield string('H')
    return any_char.times(num).concat()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment