Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Judge Python str include Chinese

Tags:

python

I want to define a function , Checks if a string is contained in Chinese. For example, check_contain_chinese("中国"), it returns True. check_contain_chinese('xx中国'), it returns True, check_contain_chinese("xxx"), it return False. Could someone give me some advice ? I'm a freshman ..

like image 574
changzhi Avatar asked May 26 '26 02:05

changzhi


2 Answers

Check for the range of unicode characters to find out if a character in string belongs to chinese characters or not. A google search tells me all chinese characters fall between '\u4e00' and u'\u9fff'. You may want to verify that yourself.

def check_contain_chinese(check_str):
    for ch in check_str.decode('utf-8'):
        if u'\u4e00' <= ch <= u'\u9fff':
            return True
    return False
like image 154
Sudipta Avatar answered May 27 '26 16:05

Sudipta


All existing answers here confused the CJK (which represents Chinese, Japanese, and Korean) characters with Han characters(which only represents Chinese) characters.

It's easy tell whether a character is CJK but harder to tell whether a character is Chinese and the standard is changing, new characters are being added always.

But in practice, people usually use u'\u4e00' - u'\u9fa5' to check whether a character. CJK characters out of that range usually can not be displayed by common Chinese fonts.

Sometimes CJK Radicals Supplement, Bopomofo, CJK Strokes should also be treated as characters, and they are not even in the CJK Unified Ideographs('\u4e00'- u'\u9fff'), but they are common and important in the Chinese writing system.

Reference:

CJK characters

CJK Unified Ideographs

Unihan Database Lookup

GB 2312 to Unicode

GB 12345 to Unicode

like image 37
Leonardo.Z Avatar answered May 27 '26 14:05

Leonardo.Z