Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check if a string contains chinese character?

A string maybe this

ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt"

or this

ipath = './data/NCDC/ciampino/6240476818161dat.txt'

How do I know the first string contains chinese?

I find this answer maybe helpful: Find all Chinese text in a string using Python and Regex

but it didn't work out:

import re
ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt"
re.findall(ur'[\u4e00-\u9fff]+', ipath) # => []
like image 369
cqcn1991 Avatar asked Jan 04 '16 08:01

cqcn1991


3 Answers

The matched string should be unicode as well

>>> import re
>>> ipath= u"./data/NCDC/上海/虹桥/9705626661750dat.txt"
>>> re.findall(r'[\u4e00-\u9fff]+', ipath)
[u'\u4e0a\u6d77', u'\u8679\u6865']
like image 98
xecgr Avatar answered Nov 14 '22 01:11

xecgr


If you just want to know whether there is a chinese character in your string you don't need re.findall, use re.search and the fact that match objects are truthy.

>>> import re
>>> ipath= u'./data/NCDC/上海/虹桥/9705626661750dat.txt'
>>> ipath2 = u'./data/NCDC/ciampino/6240476818161dat.txt'
>>> for x in (ipath, ipath2):
...     if re.search(u'[\u4e00-\u9fff]', x):
...         print 'found chinese character in ' + x
... 
found chinese character in ./data/NCDC/上海/虹桥/9705626661750dat.txt
like image 23
timgeb Avatar answered Nov 14 '22 01:11

timgeb


And for those of us who don't care for re:

>>> ipath= u"./data/NCDC/上海/虹桥/6240476818161dat.txt"
>>> for i in range(len(ipath)):
...  if ipath[i] > u'\u4e00' and ipath[i] < u'\u9fff':
...   print ipath[i]
... 
上
海
虹
桥

Edit: for the full list of Chinese characters this SO link is worth looking at as the range U+4E00..U+9FFF is not complete. What's the complete range for Chinese characters in Unicode?

like image 7
Rolf of Saxony Avatar answered Nov 14 '22 01:11

Rolf of Saxony