python通過re正則表達式切割中英文的操作
我就廢話不多說瞭,大傢還是直接看代碼吧~
import re s = 'alibaba阿裡巴巴' # 待分割字符串 en_letter = '[\u0041-\u005a|\u0061-\u007a]+' # 大小寫英文字母 zh_char = '[\u4e00-\u9fa5]+' # 中文字符 print(re.findall(zh_char,s) + re.findall(en_letter,s)) # 輸出: ['阿裡巴巴', 'alibaba']
范圍 | 說明 |
---|---|
\u4e00-\u9fa5 | 漢字的unicode范圍 |
\u0030-\u0039 | 數字的unicode范圍 |
\u0041-\u005a | 大寫字母unicode范圍 |
\u0061-\u007a | 小寫字母unicode范圍 |
補充:python–中英文混合字符串的切分(中文按字斷開,英文按單詞分開,數字按空格等特殊符號斷開)
待切分句子:
s = “12、China’s Legend Holdings will split its several business arms to go public on stock markets, the group’s president Zhu Linan said on Tuesday.該集團總裁朱利安周二表示,haha中國聯想控股將分拆其多個業務部門在股市上市,。”
切分結果:
[’12’, ‘china’, ‘s’, ‘legend’, ‘holdings’, ‘will’, ‘split’, ‘its’, ‘several’, ‘business’, ‘arms’, ‘to’, ‘go’, ‘public’, ‘on’, ‘stock’, ‘markets’, ‘the’, ‘group’, ‘s’, ‘president’, ‘zhu’, ‘linan’, ‘said’, ‘on’, ‘tuesday’, ‘該’, ‘集’, ‘團’, ‘總’, ‘裁’, ‘朱’, ‘利’, ‘安’, ‘周’, ‘二’, ‘表’, ‘示’, ‘haha’, ‘中’, ‘國’, ‘聯’, ‘想’, ‘控’, ‘股’, ‘將’, ‘分’, ‘拆’, ‘其’, ‘多’, ‘個’, ‘業’, ‘務’, ‘部’, ‘門’, ‘在’, ‘股’, ‘市’, ‘上’, ‘市’]
代碼:
import re def get_word_list(s1): # 把句子按字分開,中文按字分,英文按單詞,數字按空格 regEx = re.compile('[\\W]*') # 我們可以使用正則表達式來切分句子,切分的規則是除單詞,數字外的任意字符串 res = re.compile(r"([\u4e00-\u9fa5])") # [\u4e00-\u9fa5]中文范圍 p1 = regEx.split(s1.lower()) str1_list = [] for str in p1: if res.split(str) == None: str1_list.append(str) else: ret = res.split(str) for ch in ret: str1_list.append(ch) list_word1 = [w for w in str1_list if len(w.strip()) > 0] # 去掉為空的字符 return list_word1 if __name__ == '__main__': s = "12、China's Legend Holdings will split its several business arms to go public on stock markets, the group's president Zhu Linan said on Tuesday.該集團總裁朱利安周二表示,haha中國聯想控股將分拆其多個業務部門在股市上市。" list_word1=get_word_list(s) print(list_word1)
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- python中對正則表達式re包的簡單引用方式
- python中re模塊知識點總結
- Python正則表達re模塊之findall()函數詳解
- Java Pattern與Matcher字符串匹配案例詳解
- Java中Pattern.compile函數的使用詳解