Search code examples
pythonregexcharacter-encodingcherrypy

special characters in python output gives error message


I have a cherrypy service running that basically changes a text by another with RE, but there is a change that gives error and I can not make it work.

the code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cherrypy, re, os, sys
#define form function
    def NMT(self, contents=None):
            if not contents:
                    return """no text"""
            else:
                 contents = re.sub(r'v|V|ï', "ü" ,contents)
                 contents = re.sub(r'(S|s)d|z|Z', "d" ,contents)
                 contents = re.sub(r'(n|N)(·|d|h)', r"n'" ,contents)
                 contents = re.sub(r'(C|c)([^h])', r"ch\2" ,contents)
....

EDIT: adding the rest of the script:

# open (or create) the destination file
            with open("nmt.txt","w") as fileout:

# write all the changes into the destination file
                    fileout.write(contents)

# the result html page
            return """ done """

# define the downloading funtcion
    def download(self):
            return serve_download('/srv/web/NMT/nmt.txt')
    download.exposed = True

# expose the text area
    NMT.exposed = True

# expose the index, otherwise won't be shown
    index.exposed = True

# set service port, to not conflict with other services
cherrypy.config.update({'server.socket_host': 'www.chandia.net',
                     'server.socket_port': 8080,
                    })

# web server engine, http://www.chandia.net:8080
cherrypy.quickstart(helloworld())

The first change is the one that gives problems, the others work perfectly well, the error of the firt change is this one:

 File "/srv/web/NMT/nmt_web.py", line 88, in NMT
 contents = re.sub(r'v|V|ï', "ü" ,contents)
 File "/usr/lib/python2.7/re.py", line 151, in sub
 return _compile(pattern, flags).sub(repl, string, count)
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)

Thanks in advance for your help


Solution

  • Your program begins thus:

    #!/usr/bin/env python3
    

    but your error message says this:

     File "/usr/lib/python2.7/re.py", line 151, in sub
    

    Note the version mismatch. You are using the wrong python interpreter.