1. 程式人生 > >Python 判斷漢字

Python 判斷漢字

為了清洗資料, 專案中需要去除所有不包含中文的字串

使用 unicode 範圍 \u4e00 - \u9fff 來判別漢字

unicode 分配給漢字(中日韓越統一表意文字)的範圍為 4E00-9FFF (目前 unicode 6.3 的標準已定義到 9FCC )

在 Python 3 中,判斷字元是否漢字的方法如下:

def ishan(text):
    # for python 3.x
    # sample: ishan('一') == True, ishan('我&&你') == False
    return all('\u4e00' <= char <= '\u9fff' for char in text)

Python 2寫法

def ishan(text):
    # for python 2.x, 3.3+
    # sample: ishan(u'一') == True, ishan(u'我&&你') == False
    return all(u'\u4e00' <= char <= u'\u9fff' for char in text)

補充說明

  1. Python 3.3+ 重新支援 Python 2 中用 u 表示 unicode 的方式
  2. \u4e00-\u9fff 不包含中文符號,如有需要可參考維基
  3. 網上常見的 \u4e00-\u9fa5 寫太死了,雖說目前而言後面的都是極其罕見的字