~ubuntu-branches/ubuntu/breezy/antlr/breezy

« back to all changes in this revision

Viewing changes to examples/python/unicode/unicode.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2005-06-29 16:11:22 UTC
  • mfrom: (0.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20050629161122-g81crc3z92p5xhsg
Tags: 2.7.5-6ubuntu4
Build depend on java-gcj-compat-dev, depend on java-gcj-compat.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import sys
 
2
import antlr
 
3
import codecs
 
4
 
 
5
import unicode_l
 
6
 
 
7
def warn(msg):
 
8
   print >>sys.stderr,"warning:",msg
 
9
   sys.stderr.flush()
 
10
 
 
11
def error(msg):
 
12
   print >>sys.stderr,"error:",msg
 
13
   sys.stderr.flush()
 
14
 
 
15
### Unicode  handling  depends very much on  whether
 
16
### your  terminal can  handle (print) unicode chars.
 
17
 
 
18
### To  be  sure  about  it, just create a non ASCII
 
19
### letter and try to print it. If that is not going
 
20
### to work, we create an  alternative  method which
 
21
### maps non printable chars to '?'.
 
22
 
 
23
c = u"\N{LATIN SMALL LETTER O WITH ACUTE}"
 
24
 
 
25
try:
 
26
   print c
 
27
except UnicodeEncodeError,e:
 
28
   warn("terminal can't display unicode chars.")
 
29
   sys.stderr.flush()
 
30
 
 
31
   ## I'm just going to redefine 'unicode' to return
 
32
   ## a ASCII string.
 
33
   def unicode(x):
 
34
      return x.__str__().encode("ascii","replace")
 
35
 
 
36
 
 
37
### Now for the input. This should ideally  be  done
 
38
### in the lexer ..
 
39
 
 
40
### replace  stdin  with  a  wrapper that spits out
 
41
### unicode chars.
 
42
sys.stdin = codecs.lookup('latin1')[-2](sys.stdin)
 
43
 
 
44
try:
 
45
   for token in unicode_l.Lexer():
 
46
      print unicode(token)
 
47
except antlr.TokenStreamException, e:
 
48
   error(str(e))