Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import time
- import pprint
- from pyparsing import *
- from config import *
- from SimpleCalc import SimpleCalcInputString
- pp = pprint.PrettyPrinter(indent=4)
- ######################################
- # atoms
- ######################################
- point = Literal('.')
- plusorminus = Literal('+') | Literal('-')
- number = Word(nums)
- Integer = Combine( Optional(plusorminus) + number )
- def ValidateIntegerString(tokens):
- try:
- tokens[0] = int(tokens[0])
- except ValueError, ve:
- raise ParseException('Number is too long (%s)' % tokens[0])
- Integer.setParseAction(ValidateIntegerString)
- Float = Combine( Integer + Optional( point + Optional(number) ) )
- def ValidateFloatString(tokens):
- try:
- tokens[0] = float(tokens[0])
- except ValueError, ve:
- raise ParseException('Number is too long (%s)' % tokens[0])
- Float.setParseAction(ValidateFloatString)
- Date = Combine(number + '.' + number + '.' + number)
- def validateDateString(tokens):
- try:
- time.strptime(tokens[0], '%Y.%m.%d')
- except ValueError, ve:
- try:
- time.strptime(tokens[0], '%y.%m.%d')
- except ValueError, ve:
- raise ParseException('Invalid date string (%s)' % tokens[0])
- Date.setParseAction(validateDateString)
- calc = QuotedString(quoteChar='#')
- def validateCalcString(tokens):
- tokens[0] = SimpleCalcInputString(tokens[0], separator=';')
- calc.setParseAction(validateCalcString)
- email = Regex(r"([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)\.([A-Za-z]{2,6})")
- ######################################
- # keywords
- ######################################
- Comments = Suppress('--') + restOfLine
- Comments = Comments.setResultsName('comments')
- journalName = Word(alphanums + '.,_:&@()<>~')
- New = oneOf( 'new n', caseless=True )
- Credit = oneOf( 'credit cr', caseless=True )
- Debit = oneOf( 'debit db', caseless=True )
- Journal = oneOf( 'journal j', caseless=True )
- Balance = oneOf( 'balance b', caseless=True )
- Ammount = Float | calc
- Grant = CaselessKeyword('grant')
- permission = oneOf( 'none pend read write admin', caseless=True )
- channel = (email | number)
- ######################################
- # sentences
- ######################################
- Help = (CaselessKeyword('help') | Literal('?') | CaselessLiteral('h')) +\
- Optional(restOfLine).setResultsName('helpString')
- newJournal = StringStart() +\
- (New + Journal | CaselessKeyword('nj')) + \
- journalName.setResultsName('newJournal') + \
- ( Optional(QuotedString(quoteChar="'")\
- .setResultsName('description')) &\
- Optional(Debit + QuotedString(quoteChar="'")\
- .setResultsName('debit')) &\
- Optional(Credit + QuotedString(quoteChar="'")\
- .setResultsName('credit')) &\
- Optional(Balance + Ammount.setResultsName('balance')) &\
- Optional(Comments)) + StringEnd()
- grant = StringStart() +\
- Grant +\
- delimitedList(email).setResultsName('users') +\
- permission.setResultsName('permission') +\
- delimitedList(journalName).setResultsName('journals') +\
- StringEnd()
- testing = StringStart() +\
- CaselessKeyword('calc') + calc.setResultsName('calc') +\
- StringEnd()
- syntax = newJournal |\
- Help |\
- grant |\
- testing |\
- QuotedString(quoteChar="(*", endQuoteChar='*)').setResultsName('k9') +\
- StringEnd()
- # 1 2 3 4 5 6 7 8
- #2345678901234567890123456789012345678901234567890123456789012345678901234567890
- tests = """
- grant pedro@pablo.com none journal_1
- grant pedro@pablo.com,pablo@pedro.com none journal_1, journal_2, journal_3
- (*stop*)
- nj journal_1
- nj journal_2 db 'debito'
- nj journal_3 cr 'credito'
- nj journal_4 b #34/3#
- nj journal_5 cr 'credito' db 'debito' b 345
- new journal journal_6 balance 978 credit 'credito' debit 'debito' --comentarios
- ?
- help
- ? l ahfkljfh akjf hakljfh akjf
- help a dshkjlhdakj dhajh
- """
- for test in tests.splitlines():
- if test.strip() != '':
- linea = syntax.parseString(test)
- ldict = linea.asDict()
- if ldict.has_key('k9') and ldict['k9'] == 'stop':
- break
- print '-'*80
- pp.pprint(ldict)
- print '='*80
- #$ py k9
- #--------------------------------------------------------------------------------
- #{ 'journals': (['journal_1'], {}),
- # 'permission': 'none',
- # 'users': (['pedro@pablo.com'], {})}
- #Traceback (most recent call last):
- # File "k9.py", line 138, in <module>
- # linea = syntax.parseString(test)
- # File "/usr/local/lib/python2.7/dist-packages/pyparsing.py", line 1032, in parseString
- # raise exc
- #pyparsing.ParseException: Expected end of text (at char 54), (line:1, col:55)
- #$
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement