python篩選中日韓文

通常我們可以使用 repr()函數查看字串的原始格式。這對於寫正則表達式有所幫助。


UTF-8 是變長的,1-6個字節,少數是漢字每個佔用3個字節,多數佔用4個字節,正則式爲[\x80-\xff]{3}


re.match(), re.search 。

兩個函數的匹配過程完全一致,只是起點不同。
match只從字串的開始位置進行匹配,如果失敗,它就此放棄;

而search則會鍥而不捨地完全遍歷整個字串中所有可能的位置,直到成功地找到一個匹配,或者搜索完字串,以失敗告終。

如果你瞭解match的特性(在某些情況下比較快),大可以自由用它;如果不太清楚,search通常是你需要的那個函數。

從一堆文本中,找出所有可能的匹配,以列表的形式返回,這種情況用findall()這個函數。


如果字串不是unicode的,可以使用unicode()函數轉換之。如果你知道源字串的編碼,可以使用newstr=unicode(oldstring, original_coding_name)的方式轉換

# -*- coding: utf-8 -*- 
import sys 
import re 
reload(sys) 
sys.setdefaultencoding('utf8') 
 
 
s=""" 
 en: Regular expression is a powerful tool for manipulating text. 
 zh: 漢語是世界上最優美的語言,正則表達式是一個很有用的工具 
 jp: 正規表現は非常に役に立つツールテキストを操作することです。 
 jp-char: あアいイうウえエおオ 
 kr:정규 표현식은 매우 유용한 도구 텍스트를 조작하는 것입니다. 
 """ 
print "原始utf8字符" 
#utf8 
print "--------" 
print repr(s) 
print "--------\n" 
 
#非ansi 
re_words=re.compile(r"[\x80-\xff]+") 
m = re_words.search(s,0) 
print "非ansi字符" 
print "--------" 
print m 
print m.group() 
print "--------\n" 
 
#unicode 
s = unicode(s) 
print "原始unicode字符" 
print "--------" 
print repr(s) 
print "--------\n" 
 
#unicode chinese 
re_words = re.compile(u"[\u4e00-\u9fa5]+") 
m = re_words.search(s) 
print "unicode 中文" 
print "--------" 
print m 
print m.group() 
res = re.findall(re_words, s) # 查詢出所有的匹配字符串 
if res: 
 print "There are %d parts:\n"% len(res) 
 for r in res: 
 print "\t",r 
 print 
print "--------\n" 
 
 
#unicode korean 
re_words=re.compile(u"[\uac00-\ud7ff]+") 
m = re_words.search(s,0) 
print "unicode 韓文" 
print "--------" 
print m 
print m.group() 
print "--------\n" 
 
 
#unicode japanese katakana 
re_words=re.compile(u"[\u30a0-\u30ff]+") 
m = re_words.search(s,0) 
print "unicode 日文 片假名" 
print "--------" 
print m 
print m.group() 
print "--------\n" 
 
 
#unicode japanese hiragana 
re_words=re.compile(u"[\u3040-\u309f]+") 
m = re_words.search(s,0) 
print "unicode 日文 平假名" 
print "--------" 
print m 
print m.group() 
print "--------\n" 
 
 
#unicode cjk Punctuation 
re_words=re.compile(u"[\u3000-\u303f\ufb00-\ufffd]+") 
m = re_words.search(s,0) 
print "unicode 標點符號" 
print "--------" 
print m 
print m.group() 
print "--------\n"

匹配中文簡體和繁體:        ^[\u4E00-\u9FFF]+$

匹配中文簡體:                   ^[\u4E00-\u9FA5]+$

匹配日文平假名:               ^[\u3040-\u309f]+$

匹配日文片假名:               ^[\u30a0-\u30ff]+$

匹配韓文:                           ^[\uac00-\ud7ff]+$



發佈了105 篇原創文章 · 獲贊 82 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章