Reputation: 2709
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 ..
Upvotes: 3
Views: 560
Reputation: 9801
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:
Upvotes: 3
Reputation: 10807
There is six Unicode maps for Chinese characters. Just check if code of any character in your string fits the 0x4E00 - 0x9FFF interval:
>>> any(0x4E00 <= ord(x) <= 0x9FFF for x in u'xx中国')
1: True
>>> any(0x4E00 <= ord(x) <= 0x9FFF for x in u'xxx')
2: False
Upvotes: 2
Reputation: 4971
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
Upvotes: 5