Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

# Untitled

By: a guest on Mar 25th, 2012  |  syntax: None  |  size: 4.98 KB  |  views: 36  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. #!/usr/bin/env python
2.
3. import time
4. import pprint
5.
6. from pyparsing import *
7.
8. from config import *
9. from SimpleCalc import SimpleCalcInputString
10.
11. pp = pprint.PrettyPrinter(indent=4)
12.
13. ######################################
14. #   atoms
15. ######################################
16. point = Literal('.')
17.
18. plusorminus = Literal('+') | Literal('-')
19.
20. number = Word(nums)
21.
22. Integer = Combine( Optional(plusorminus) + number )
23. def ValidateIntegerString(tokens):
24.     try:
25.         tokens[0] = int(tokens[0])
26.     except ValueError, ve:
27.         raise ParseException('Number is too long (%s)' % tokens[0])
28. Integer.setParseAction(ValidateIntegerString)
29.
30. Float = Combine( Integer + Optional( point + Optional(number) ) )
31. def ValidateFloatString(tokens):
32.     try:
33.         tokens[0] = float(tokens[0])
34.     except ValueError, ve:
35.         raise ParseException('Number is too long (%s)' % tokens[0])
36. Float.setParseAction(ValidateFloatString)
37.
38. Date = Combine(number + '.' + number + '.' + number)
39. def validateDateString(tokens):
40.     try:
41.         time.strptime(tokens[0], '%Y.%m.%d')
42.     except ValueError, ve:
43.         try:
44.             time.strptime(tokens[0], '%y.%m.%d')
45.         except ValueError, ve:
46.             raise ParseException('Invalid date string (%s)' % tokens[0])
47. Date.setParseAction(validateDateString)
48.
49. calc = QuotedString(quoteChar='#')
50. def validateCalcString(tokens):
51.     tokens[0] = SimpleCalcInputString(tokens[0], separator=';')
52. calc.setParseAction(validateCalcString)
53.
54. email = Regex(r"([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)\.([A-Za-z]{2,6})")
55.
56. ######################################
57. #   keywords
58. ######################################
59. Comments = Suppress('--') + restOfLine
61.
62. journalName = Word(alphanums + '.,_:&@()<>~')
63.
64. New = oneOf( 'new n', caseless=True  )
65.
66. Credit = oneOf( 'credit cr', caseless=True )
67.
68. Debit = oneOf( 'debit db', caseless=True )
69.
70. Journal = oneOf( 'journal j', caseless=True  )
71.
72. Balance = oneOf( 'balance b', caseless=True  )
73.
74. Ammount = Float | calc
75.
76. Grant = CaselessKeyword('grant')
77.
79.
80. channel = (email | number)
81.
82. ######################################
83. #   sentences
84. ######################################
85. Help =  (CaselessKeyword('help') | Literal('?') | CaselessLiteral('h')) +\
86.          Optional(restOfLine).setResultsName('helpString')
87.
88. newJournal =    StringStart() +\
89.                 (New + Journal | CaselessKeyword('nj')) + \
90.                 journalName.setResultsName('newJournal') + \
91.                 (   Optional(QuotedString(quoteChar="'")\
92.                                             .setResultsName('description')) &\
93.                     Optional(Debit + QuotedString(quoteChar="'")\
94.                                             .setResultsName('debit')) &\
95.                     Optional(Credit + QuotedString(quoteChar="'")\
96.                                             .setResultsName('credit')) &\
97.                     Optional(Balance + Ammount.setResultsName('balance')) &\
99.
100. grant = StringStart() +\
101.         Grant +\
102.         delimitedList(email).setResultsName('users') +\
103.         permission.setResultsName('permission') +\
104.         delimitedList(journalName).setResultsName('journals') +\
105.         StringEnd()
106.
107. testing = StringStart() +\
108.           CaselessKeyword('calc') + calc.setResultsName('calc') +\
109.           StringEnd()
110.
111. syntax = newJournal |\
112.          Help |\
113.          grant |\
114.          testing |\
115.          QuotedString(quoteChar="(*", endQuoteChar='*)').setResultsName('k9') +\
116.          StringEnd()
117.
118. #        1         2         3         4         5         6         7         8
119. #2345678901234567890123456789012345678901234567890123456789012345678901234567890
120. tests = """
121. grant pedro@pablo.com none journal_1
122. grant pedro@pablo.com,pablo@pedro.com none journal_1, journal_2, journal_3
123. (*stop*)
124. nj journal_1
125. nj journal_2 db 'debito'
126. nj journal_3 cr 'credito'
127. nj journal_4 b #34/3#
128. nj journal_5 cr 'credito' db 'debito' b 345
129. new journal journal_6 balance 978 credit 'credito' debit 'debito'  --comentarios
130. ?
131. help
132. ? l ahfkljfh akjf hakljfh akjf
133. help a dshkjlhdakj dhajh
134. """
135.
136. for test in tests.splitlines():
137.     if test.strip() != '':
138.         linea = syntax.parseString(test)
139.         ldict = linea.asDict()
140.         if ldict.has_key('k9') and ldict['k9'] == 'stop':
141.             break
142.         print '-'*80
143.         pp.pprint(ldict)
144. print '='*80
145.
146.
147. #\$ py k9
148. #--------------------------------------------------------------------------------
149. #{   'journals': (['journal_1'], {}),
150. #    'permission': 'none',
151. #    'users': (['pedro@pablo.com'], {})}
152. #Traceback (most recent call last):
153. #  File "k9.py", line 138, in <module>
154. #    linea = syntax.parseString(test)
155. #  File "/usr/local/lib/python2.7/dist-packages/pyparsing.py", line 1032, in parseString
156. #    raise exc
157. #pyparsing.ParseException: Expected end of text (at char 54), (line:1, col:55)
158. #\$
clone this paste RAW Paste Data
Top