1 #coding=utf-8 2 import re 3 import chardet#檢測網頁編碼形式的模塊 4 5 p = re.compile(r'\d+') 6 print p.findall('one1two2three3four4') 7 8 a="rewfd231321ewq21weqeqw" 9 p=re.compile(r"(\d+)\D+(\d+)",re.S) 10 b=p.findall(a) 11 print b 12 13 a=u"我愛@糗百,你呢" 14 print a 15 b=re.findall (u"(.+?)@糗百(.+)",a,re.S) 16 print b 17 for i in b: 18 for j in i: 19 print j
結果:
['1', '2', '3', '4']
[('231321', '21')] #findall的結果是[(),()]這種形式的,如果元組只有一個元素,則是["",""]這樣子的
我愛@糗百,你呢
[(u'\u6211\u7231', u'\uff0c\u4f60\u5462')]
我愛
,你呢
——————————————————————————————————————————
如果不知道漢字文本的編碼,比如說是一段網上爬來的文字(通常情況下就是不知道的)
1 import re 2 import chardet#檢測網頁編碼形式的模塊 3 4 a="我愛@糗百,你呢" 5 if isinstance(a, unicode) : 6 pass 7 else: 8 codesty=chardet.detect(a) 9 a=a.decode(codesty['encoding']) 10 print a 11 b=re.findall (u"(.+?)@糗百(.+)",a,re.S) 12 print b 13 for i in b: 14 for j in i: 15 print j
則利用chardet這個模塊得到它的編碼,並將其轉化為unicode
結果:
我愛@糗百,你呢
[(u'\u6211\u7231', u'\uff0c\u4f60\u5462')]
我愛
,你呢
當然,如果想雙擊,py在windows下演示,得到的字符串應該再加j.encode("GBK")
注意:處理中文前要將其轉化為unicode,不要ascii碼直接正則匹配,ascII碼如何轉Unicode?遇到再說吧~