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) # => []
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']
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With