天天看点

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