python中可以通过判断字符的unicode值来判断字符是不是中文字符。
defis_chinese(uchar): """判断一个unicode是否是汉字""" ifuchar>=u'/u4e00'anduchar<=u'/u9fa5': returnTrue else: returnFalse defis_number(uchar): """判断一个unicode是否是数字""" ifuchar>=u'/u0030'anduchar<=u'/u0039': returnTrue else: returnFalse defis_alphabet(uchar): """判断一个unicode是否是英文字母""" if(uchar>=u'/u0041'anduchar<=u'/u005a')or(uchar>=u'/u0061'anduchar<=u'/u007a'): returnTrue else: returnFalse defis_other(uchar): """判断是否非汉字,数字和英文字符""" ifnot(is_chinese(uchar)oris_number(uchar)oris_alphabet(uchar)): returnTrue else: returnFalse defB2Q(uchar): """半角转全角""" inside_code=ord(uchar) ifinside_code<0x0020orinside_code>0x7e:#不是半角字符就返回原来的字符 returnuchar ifinside_code==0x0020:#除了空格其他的全角半角的公式为:半角=全角-0xfee0 inside_code=0x3000 else: inside_code+=0xfee0 returnunichr(inside_code) defQ2B(uchar): """全角转半角""" inside_code=ord(uchar) ifinside_code==0x3000: inside_code=0x0020 else: inside_code-=0xfee0 ifinside_code<0x0020orinside_code>0x7e:#转完之后不是半角字符返回原来的字符 returnuchar returnunichr(inside_code) defstringQ2B(ustring): """把字符串全角转半角""" return"".join([Q2B(uchar)forucharinustring]) defuniform(ustring): """格式化字符串,完成全角转半角,大写转小写的工作""" returnstringQ2B(ustring).lower() defstring2List(ustring): """将ustring按照中文,字母,数字分开""" retList=[] utmp=[] forucharinustring: ifis_other(uchar): iflen(utmp)==0: continue else: retList.append("".join(utmp)) utmp=[] else: utmp.append(uchar) iflen(utmp)!=0: retList.append("".join(utmp)) returnretList if__name__=="__main__": #testQ2BandB2Q foriinrange(0x0020,0x007F): printQ2B(B2Q(unichr(i))),B2Q(unichr(i)) #testuniform ustring=u'中国人名a高频A' ustring=uniform(ustring) ret=string2List(ustring) printret原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容