python去除中文字之間的空格,保留英文單詞之間的空格【轉】


正則表達式去除中文字之間的空格,保留英文單詞之間的空格,對於英文單詞中間夾雜着數字的情況,應該保留空格但沒有保留

 # -*- coding:utf-8 -*- #
import re

def _clean_space(text): ​ match_regex = re.compile(u'[\u4e00-\u9fa5。\.,,::《》、\(\)()]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+') ​ should_replace_list = match_regex.findall(text) ​ order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True) ​ for i in order_replace_list: ​ if i == u' ': ​ continue ​ new_i = i.strip() ​ text = text.replace(i,new_i) ​ return text text = "從大約40萬 年前開始,一個關鍵的環境轉變 發生了。hello world!" text=text.decode("utf-8") text=_clean_space(text).encode("utf-8") print(text)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM