python怎么判断是不是中文字符?
发布时间:2026-02-01 21:52:38

在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,0x07F):
printQ2B(B2Q(unichr(i))),B2Q(unichr(i))
#testuniform
ustring=u'中国人名a高频A'
ustring=uniform(ustring)
ret=string2List(ustring)
printret请关注Python自学网了解更多Python知识。
