如何将一个字符串中的全角字符转化为半角?字符串可能包含中文。

4 views
Skip to first unread message

Jingwei Sun

unread,
Mar 25, 2009, 1:31:09 AM3/25/09
to pyth...@googlegroups.com

我参考了一些资料,不过还是有问题:
# -*- coding: cp936 -*-

def B2Q(uchar):
        """半角转全角"""
        inside_code=ord(uchar)
        if inside_code<0x0020 or inside_code>0x7e:      #不是半角字符就返回原来的字符
                return uchar
        if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
                inside_code=0x3000
        else:
                inside_code+=0xfee0
        return unichr(inside_code)

def Q2B(uchar):
        """全角转半角"""
        inside_code=ord(uchar)
        if inside_code==0x3000:
                inside_code=0x0020
        else:
                inside_code-=0xfee0
        if inside_code<0x0020 or inside_code>0x7e:      #转完之后不是半角字符返回原来的字符
                return uchar
        return unichr(inside_code)

def uniform(ustring):
    '''
    uniform():用来将制定的字符串中的全角转化为半角。
    '''
    return "".join([Q2B(uchar) for uchar in ustring])


if __name__=="__main__":
    temp=u'Abhello,world!中国safds'
    print uniform(temp)
    temp=raw_input('input a string:')
    print uniform(temp)


最后的输出为:
Abhello,world!中国safds
input a string:Abhello,world!中国safds
Abhello,world!中国safds

最后的 temp=u'Abhello,world!中国safds'可以直接print出来。
不过从raw_input之后的输出仍然包含全角的字符。为什么呢?

多谢了先。

--
**********************
海角天涯
            永远追随
http://logo.yo2.cn
**********************

SunShine

unread,
Mar 25, 2009, 1:40:26 AM3/25/09
to python-cn`CPyUG`华蟒用户组
raw_input读入的字符如何转化为unicode格式的呢?
我试过unicode(temp)然后再调用uniform函数也是不行的。

> *最后的输出为:*

anny raul

unread,
Mar 25, 2009, 1:45:24 AM3/25/09
to pyth...@googlegroups.com
>>> s = raw_input("input:")
input:汉字
>>> s
'\xba\xba\xd7\xd6'
>>> b = unicode(s.decode('gbk'))
>>> b
u'\u6c49\u5b57'

跟你系统环境有关,偶是win这么尝试就ok了

2009/3/25 SunShine <jingw...@gmail.com>
raw_input读入的字符如何转化为unicode格式的呢?
我试过unicode(temp)然后再调用uniform函数也是不行的。


--
anny raul <anny...@gmail.com>
http://annyraul.blogspot.com

SunShine

unread,
Mar 25, 2009, 11:23:45 PM3/25/09
to python-cn`CPyUG`华蟒用户组
windows下是可以的,为何linux下不行呢?

temp=u'Abhello,world!中国safds'
print uniform(temp)

这个运行提示错误:
Traceback (most recent call last):
File "trans2.py", line 34, in ?
print uniform(temp)
UnicodeError: ASCII encoding error: ordinal not in range(128)

为什么呢?
我的 $LANG为“en_US.”

On 3月25日, 下午1时45分, anny raul <annyr...@gmail.com> wrote:
> >>> s = raw_input("input:")
> input:汉字
> >>> s
> '\xba\xba\xd7\xd6'
> >>> b = unicode(s.decode('gbk'))
> >>> b
>
> u'\u6c49\u5b57'
>
> 跟你系统环境有关,偶是win这么尝试就ok了
>

> 2009/3/25 SunShine <jingwei...@gmail.com>
>
> > raw_input读入的字符如何转化为unicode格式的呢?
> > 我试过unicode(temp)然后再调用uniform函数也是不行的。
>
> --
> anny raul <annyr...@gmail.com>http://annyraul.blogspot.com

Reply all
Reply to author
Forward
0 new messages