V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
twor2
V2EX  ›  Python

python2.7 的中文处理 报错,已解决,求大大解释原因

  •  
  •   twor2 · 2015-04-21 00:27:23 +08:00 · 3744 次点击
    这是一个创建于 3290 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # -*- coding: utf-8 -*-
    from django.utils.encoding import  python_2_unicode_compatible
    
    @python_2_unicode_compatible
    class Label(models.Model):
        width = models.ForeignKey(PaperWidth, verbose_name='宽度')
        height = models.ForeignKey(PaperHeight, verbose_name='高度')
    
        def __str__(self):
            return u'{0}({1}×{2})'.format(self.paper_type, self.width, self.height)
    

    这个是一个 python 2.7,django1.8 的程序

    之前 verbose_name=u'宽度' 在添加 @python_2_unicode_compatible 就去掉u了,没有问题

    但下面的 return u'{0}({1}×{2})' 为什么不能去掉呢?去掉就报错

    'ascii' codec can't decode byte 0xe9 in position 0
    
    第 1 条附言  ·  2015-04-21 01:36:44 +08:00
    ```
    def python_2_unicode_compatible(klass):
    """
    A decorator that defines __unicode__ and __str__ methods under Python 2.
    Under Python 3 it does nothing.

    To support Python 2 and 3 with a single code base, define a __str__ method
    returning text and apply this decorator to the class.
    """
    if six.PY2:
    if '__str__' not in klass.__dict__:
    raise ValueError("@python_2_unicode_compatible cannot be applied "
    "to %s because it doesn't define __str__()." %
    klass.__name__)
    klass.__unicode__ = klass.__str__
    klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
    return klass
    ```
    13 条回复    2015-04-22 12:18:27 +08:00
    ryd994
        1
    ryd994  
       2015-04-21 01:26:14 +08:00
    python3大法好 utf8保平安
    其实是)是全角字符的原因
    换成)就好
    ryd994
        2
    ryd994  
       2015-04-21 01:26:50 +08:00
    另外乘号也是,别告诉我你不知道要用*
    twor2
        3
    twor2  
    OP
       2015-04-21 01:29:55 +08:00
    @ryd994 谢谢亲的回答

    那为什么上面的 中文(比如 ’宽度‘) 就可以不加 u 呢

    这个 @python_2_unicode_compatible 不能解决 全角字符吗?
    twor2
        4
    twor2  
    OP
       2015-04-21 01:35:50 +08:00
    ```
    def python_2_unicode_compatible(klass):
    """
    A decorator that defines __unicode__ and __str__ methods under Python 2.
    Under Python 3 it does nothing.

    To support Python 2 and 3 with a single code base, define a __str__ method
    returning text and apply this decorator to the class.
    """
    if six.PY2:
    if '__str__' not in klass.__dict__:
    raise ValueError("@python_2_unicode_compatible cannot be applied "
    "to %s because it doesn't define __str__()." %
    klass.__name__)
    klass.__unicode__ = klass.__str__
    klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
    return klass
    ```
    twor2
        5
    twor2  
    OP
       2015-04-21 01:38:54 +08:00
    看不懂~~
    no13bus
        6
    no13bus  
       2015-04-21 08:58:56 +08:00   ❤️ 1
    @twor2 记着 中文前面加 u 就行了。还有不知道你现在的系统是什么,不要在windows下面开发python程序。
    zerh925
        7
    zerh925  
       2015-04-21 09:35:26 +08:00   ❤️ 1
    可以试试'宽度'.encode('utf-8')
    iamxi
        8
    iamxi  
       2015-04-21 10:09:36 +08:00   ❤️ 1
    如果你用win8或以上,如果你的系统用户名是中文,如果你安装了阿里旺旺,我告诉你个秘密,你还会更痛苦。所以啊,要么在linux上开发,要么换python3吧。不然你会发现各种因为字符集问题引起的古怪的问题。比如pip不能安装,及时安装上了,pip也不能安装其他模块,等等。。。。
    angeloce
        9
    angeloce  
       2015-04-21 10:56:44 +08:00   ❤️ 1
    原因很简单, python_2_unicode_compatible里写着呢.
    通过__dict__得到函数内所有的变量, 不是unicode的就decode.
    但是return xxxx 是在__dict__里得不到的, 你可以改成 result='{0}({1}×{2})'; return result 试试, 应该就可以了

    P.S. django提供这种工具好无聊, python2还是尽量在字符前加u
    twor2
        10
    twor2  
    OP
       2015-04-21 11:40:08 +08:00
    @angeloce 恩,还有一点不明白

    要访问类里的变量( 比如 width ),都要经过 return 吗?
    twor2
        11
    twor2  
    OP
       2015-04-21 11:41:31 +08:00
    @iamxi 我前几天用的python ,除了中文处理好一点,其他 的对于新手来说,坑更多。很多包都找不到,或者改名,或者替换。

    心累
    twor2
        12
    twor2  
    OP
       2015-04-21 11:42:32 +08:00
    @zerh925
    @no13bus 谢谢!,中文前面全加 u ,如果用了python3 是不是还要逐一去掉?
    no13bus
        13
    no13bus  
       2015-04-22 12:18:27 +08:00
    @twor2 奥。没用过Python3. 不太清楚。编码问题自己搞明白了就好。3和2的区别不仅仅是编码。尽量用大家都用的版本,否则遇到问题了,不好解决
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3335 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 12:30 · PVG 20:30 · LAX 05:30 · JFK 08:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.