python输出中的特殊字符给出错误消息

时间:2014-06-24 17:49:49

标签: python regex character-encoding cherrypy

我有一个运行的cherrypy服务,它基本上用RE替换了另一个文本,但是有一个更改会产生错误,我无法使其工作。

代码:

#!/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)
....

编辑:添加脚本的其余部分:

# 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())

第一个变化是给出问题的那个,其他变化很好,变化的错误是这个:

 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)

提前感谢您的帮助

1 个答案:

答案 0 :(得分:3)

您的计划从此开始:

#!/usr/bin/env python3

但是您的错误消息说明了这一点:

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

请注意版本不匹配。您正在使用错误的python解释器。