文本清洗正则表达式(持续更新)

常用但记不住的pattern

pattern description
[\u4e00-\u9fa5] 中文
\s 任何空白字符
\S 任何非空白字符
(?=pattern) 正向肯定预查
(?<=pattern) 反向肯定预查
(?!pattern) 正向否定预查
(?<!pattern) 反向否定预查
\w 中英文数字下划线

正向肯定预查

import re
rc = re.compile('小米(?=手机)')
print(rc.fullmatch('小米手机'))  # None
print(rc.fullmatch('小米'))  # None
print(rc.findall('小米手机'))  # ['小米']
print(rc.findall('小米粥'))  # []

\w

import re
rec = re.compile('\w')
a = 'aA1啊の.\n,。_+-='
print(rec.findall(a))  # 日文也属于\w
# ['a', 'A', '1', '啊', 'の', '_']
print(list(rec.sub('', a)))
# ['.', '\n', ',', '。', '+', '-', '=']

特殊字符清洗

import re

a = '''𠙶山aA11,./<>?";':[]{}\\|`~!@#$%^&*()_+-=《》?,。/:;’‘”“【】、·!@=#=¥%=…()—❤'''

rc = re.compile(r'[^-_a-zA-Z\d\u4e00-\u9fa5\s,<.>/?;:"\[{\]}|`~!@#$%^&*()=+,《。》?;:‘’“”【】、·!¥…()—]')  # 少'\
print(rc.findall(a))
# ['𠙶', "'", '\\', '❤']

rc = re.compile(r'[^-\w\s,<.>/?;:\'"\[{\]}\\|`~!@#$%^&*()=+,《。》?;:‘’“”【】、·!¥…()—]')
print(rc.findall(a))
# ['❤']

清除连续空白符

def replace_continuous_blank_lines(text):
    """清除连续空行"""
    return re.sub(r'\n\s*\n', '\n', text.strip())

def replace_space(text):
    """清除连续空白"""
    text = re.sub(r'\s*\n\s*', '\n', text.strip())
    text = re.sub(r'[^\S\n]', ' ', text)
    text = re.sub('(?<![\u4e00-\u9fa5]) (?=[\u4e00-\u9fa5])|(?<=[\u4e00-\u9fa5]) (?![\u4e00-\u9fa5])', '', text)
    return text

def replace_space_resolutely(text, substitution=''):
    return re.sub(r'\s+', substitution, text.strip())

HTML标签清洗

def replace_tag(html, completely=True):
    """替换HTML标签"""
    # 独立元素
    html = re.sub('<img[^>]*>', '', html)  # 图片
    html = re.sub('<br/?>|<br [^<>]*>|<hr/?>|<hr [^<>]*>', '\n'
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值