天天看點

Python:用正規表達式,提取字元串中的所有中文 - ShineLe

Python:用正規表達式,提取字元串中的所有中文

2021-01-30 12:56 

ShineLe 

閱讀(800) 

評論(0) 

編輯 

收藏 

舉報

import re

def clean(line):
    pattern = re.compile(u\'[^\u4e00-\u9fa5]\') #中文的範圍為\u4e00-\u9fa5
    line = re.sub(pattern,\'\',line) #将其中所有非中文字元替換
    return line

with open(\'《邊城》.txt\' , \'r\' , encoding=\'utf-8\') as f:
    s=f.read() #讀取原文本
    s=clean(s) #删除其中符号、數字等非中文字元      
  • 分類 Python
Python:用正規表達式,提取字元串中的所有中文 - ShineLe