2016-01-04 137 views
6

的字符串,也許這Python:檢查一個字符串是否包含漢字?

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

或本

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

我怎麼知道第一個字符串包含中國

我覺得這個答案也許有幫助: Find all Chinese text in a string using Python and Regex

,但它沒有工作:

import re 
ipath= "./data/NCDC/上海/虹橋/9705626661750dat.txt" 
re.findall(ur'[\u4e00-\u9fff]+', ipath) # => [] 
+0

你使用Python 2嗎?在Python 3中,當聲明正則表達式時,[似乎工作](https://ideone.com/lPHSky)沒有'r'。 –

+3

'ipath = u「./ data/NCD',錯過字符串前的'u' – Tushar

+1

看看這個[Python 2 demo](https://ideone.com/i0unNw) - 它適合你嗎? –

回答

7

匹配的字符串應該是Unicode以及

>>> import re 
>>> ipath= u"./data/NCDC/上海/虹橋/9705626661750dat.txt" 
>>> re.findall(ur'[\u4e00-\u9fff]+', ipath) 
[u'\u4e0a\u6d77', u'\u8679\u6865'] 
1
import re 
ipath= raw_input() 
print re.findall(ur'[\u4e00-\u9fff]+', ipath.decode("utf-8")) 

輸出:./data/NCDC/上海/虹橋/9705626661750dat.txt [u'\u4e0a\u6d77', u'\u8679\u6865']

您需要對輸入進行解碼才能使其成爲unicode。

import re 
ipath= unicode(raw_input(),encoding="utf-8") 
print re.findall(ur'[\u4e00-\u9fff]+', ipath) 
1

''是Python的2字節字符串無論是在模塊的頂部添加from __future__ import unicode_literals或使用unicode文字:u''

>>> import re 
>>> ipath= u"./data/NCDC/上海/虹橋/9705626661750dat.txt" 
>>> re.findall(ur'[\u4e00-\u9fff]+', ipath) 
[u'\u4e0a\u6d77', u'\u8679\u6865'] 
1

如果你只是想知道是否在你的字符串中有一箇中文字符,你不需要re.findall,使用re.search以及匹配對象是真的。

>>> 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 
3

而對於我們這些誰不關心re

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

編輯:爲中國漢字的完整列表,此SO環節是值得考慮的是U + 4E00的範圍內。 .U + 9FFF不完整。
What's the complete range for Chinese characters in Unicode?

相關問題