正则表达式练习

练习测试网站:https://regexr.com/
正则表达式进阶练习:https://alf.nu/RegexGolf
答案参考:https://blog.csdn.net/NJYR21/article/details/79600217
. :匹配除换行符以外所有字符
\d{2}:匹配指定长度的数字
\d{2,4}:贪婪匹配2-4
d也你可以为w等
abd?:匹配其中ab/abd等(d出现0次或一次)
abc*:匹配c 0次或无限次
abc+ : 匹配c 至少一次
a(bc)+ : 匹配bc 至少一次
[acd]:指定需要的字符,a,c,d每个都会查找匹配
(…).*\1:匹配所有类似abc***abc类的字符(前变匹配的三个出现后边也出现)

^(?!.(.)(.)\2\1):匹配所有非abba类型的字符串
^(.)(.).
\2\1$:匹配所有回文

sub函数可用来进行替换
subn完成替换后可返回替换词数

在这里插入图片描述

练习1

def clean_email_text(text):
    text = text.replace('\n',' ')           #去掉换行符
    text = re.sub("-"," ",text)             #用空格替换掉‘-’
    text = re.sub(r"\d+/\d+/\d+"," " ,text)  #去掉日期数据
    text = re.sub(r"[0-2]?[0-9]:[0-6][0-9]", "", text)  # 时间,没意义
    text = re.sub(r"[\w]+@[\.\w]+", "", text)  # 邮件地址,没意义
    text = re.sub(r"/[a-zA-Z]*[:\//\]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i", "", text)  # 网址,没意义
    pure_text = ''
    # 以防还有其他特殊字符(数字)等等,我们直接把他们loop一遍,过滤掉
    for letter in text:
        # 只留下字母和空格
        if letter.isalpha() or letter == ' ':
            pure_text += letter
    # 再把那些去除特殊字符后落单的单词,直接排除。
    # 我们就只剩下有意义的单词了。
    text = ' '.join(word for word in pure_text.split() if len(word) > 1)
    return text

练习2

#定义降噪函数
def removeNoise(document):
    noise_patten = re.compile('|'.join(['http\S+','\@\w+','\#\w+']))
    clean_text = re.sub(noise_patten,'',document)
    return clean_text.strip()

print(removeNoise("Trump images are now more popular than cat gifs. @trump trends http://www.trumptrends.html"))

输出:
Trump images are now more popular than cat gifs.
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值