python判断是不是中文字符的方法
小编给大家分享一下python判断是不是中文字符的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
python中可以通过判断字符的unicode值来判断字符是不是中文字符。
defis_chinese(uchar):"""判断一个unicode是否是汉字"""ifuchar>=u'/u4e00'anduchar<=u'/u9fa5':returnTrueelse:returnFalsedefis_number(uchar):"""判断一个unicode是否是数字"""ifuchar>=u'/u0030'anduchar<=u'/u0039':returnTrueelse:returnFalsedefis_alphabet(uchar):"""判断一个unicode是否是英文字母"""if(uchar>=u'/u0041'anduchar<=u'/u005a')or(uchar>=u'/u0061'anduchar<=u'/u007a'):returnTrueelse:returnFalsedefis_other(uchar):"""判断是否非汉字,数字和英文字符"""ifnot(is_chinese(uchar)oris_number(uchar)oris_alphabet(uchar)):returnTrueelse:returnFalsedefB2Q(uchar):"""半角转全角"""inside_code=ord(uchar)ifinside_code<0x0020orinside_code>0x7e:#不是半角字符就返回原来的字符returnucharifinside_code==0x0020:#除了空格其他的全角半角的公式为:半角=全角-0xfee0inside_code=0x3000else:inside_code+=0xfee0returnunichr(inside_code)defQ2B(uchar):"""全角转半角"""inside_code=ord(uchar)ifinside_code==0x3000:inside_code=0x0020else:inside_code-=0xfee0ifinside_code<0x0020orinside_code>0x7e:#转完之后不是半角字符返回原来的字符returnucharreturnunichr(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:continueelse:retList.append("".join(utmp))utmp=[]else:utmp.append(uchar)iflen(utmp)!=0:retList.append("".join(utmp))returnretListif__name__=="__main__":#testQ2BandB2Qforiinrange(0x0020,0x007F):printQ2B(B2Q(unichr(i))),B2Q(unichr(i))#testuniformustring=u'中国人名a高频A'ustring=uniform(ustring)ret=string2List(ustring)printret
看完了这篇文章,相信你对python判断是不是中文字符的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。