File: listAllMatches.py

package info (click to toggle)
pyparsing 1.5.6%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,220 kB
  • sloc: python: 13,752; makefile: 33; sh: 17
file content (52 lines) | stat: -rw-r--r-- 1,760 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# listAllMatches.py
#
# Sample program showing how/when to use listAllMatches to get all matching tokens in a results name.
#
# copyright 2006, Paul McGuire
#

from pyparsing import oneOf, OneOrMore, printables, StringEnd

test = "The quick brown fox named 'Aloysius' lives at 123 Main Street (and jumps over lazy dogs in his spare time)."
nonAlphas = [ c for c in printables if not c.isalpha() ]

print "Extract vowels, consonants, and special characters from this test string:"
print "'" + test + "'"
print

print "Define grammar using normal results names"
print "(only last matching symbol is saved)"
vowels = oneOf(list("aeiouy"), caseless=True).setResultsName("vowels")
cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True).setResultsName("cons")
other = oneOf(list(nonAlphas)).setResultsName("others")
letters = OneOrMore(cons | vowels | other) + StringEnd()

results = letters.parseString(test)
print results
print results.vowels
print results.cons
print results.others
print


print "Define grammar using results names, with listAllMatches=True"
print "(all matching symbols are saved)"
vowels = oneOf(list("aeiouy"), caseless=True).setResultsName("vowels",listAllMatches=True)
cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True).setResultsName("cons",listAllMatches=True)
other = oneOf(list(nonAlphas)).setResultsName("others",listAllMatches=True)

letters = OneOrMore(cons | vowels | other) + StringEnd()

results = letters.parseString(test)
print results
print sorted(list(set(results)))
print
print results.vowels
print sorted(list(set(results.vowels)))
print
print results.cons
print sorted(list(set(results.cons)))
print
print results.others
print sorted(list(set(results.others)))