python 2.7 如何判断 Unicode 编码字符是否为汉字,如何判断unicode编码句子中是否含...
source link: https://blog.popkx.com/python-2-7-how-to-judge-is-an-unicode-char-chinese-char-and-if-a-sentence-chinese-char-inside/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
python 2.7 如何判断 Unicode 编码字符是否为汉字,如何判断unicode编码句子中是否含有汉字
对于计算机来说,一切都是 0 1 组成的数字,汉字也不例外。因此对于 python 来说,汉字也是可以比较大小的,所以,判断一个 unicode字符是否汉字,只需要判断该字符是否在第一个汉字
和最后一个汉字
之间即可。
查阅资料,发现对于Unicode编码的汉字,最小为 \u4e00
,最大为 \u9fa5
,所以,自然的,python 判断一个Unicode字符是否为汉字的代码可以如下写:
def IsChineseChar(uchar):
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
return False
print IsChineseChar(u'A'), IsChineseChar(u'我')
发现符合预期:
# python t.py
False True
进一步的,如果想用python判断一句unicode编码的话中是否含有中文,代码可以如下写:
def IsChineseCharInside(sentence):
for uchar in sentence:
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
return False
最终测试完整代码如下:
#encoding=utf8
def IsChineseChar(uchar):
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
return False
def IsChineseCharInside(sentence):
for uchar in sentence:
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
return False
print IsChineseChar(u'A'), IsChineseChar(u'我')
print IsChineseCharInside(u'Aasdas fsaf vs'), IsChineseCharInside(u'dasdf 我asd das')
# python t.py
False True
False True
阅读更多: Python
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK