Python 基础 —— re:正则表达

来源:互联网 发布:2017恩智浦智能车算法 编辑:程序博客网 时间:2024/05/16 03:03
  • 去除所有的 html 标签

    re.compile(r'<[^>]+>').sub('', html)                            # sub:表示 substitute,替换
  • 去除所有的非字母

    re.sub('[^a-zA-Z]', ' ', text)

1. re.search(re, str):寻找符合正则的子串本身

我们要移除如下字符串中的数字:

>>> raw = 'Toy Story (1995)'

(已知数字仅出现在最右侧,表达电影的年份)

>>> grps = re.search('\((\w+)\)', raw)>>> grps<_sre.SRE_Match object at 0x01A19960>

如果此时未在字符串中找到字符匹配,re.search() 的返回为 NoneType 对象,对 NoneType 对象进行任何操作,显然都是非法的。所以一定要对 re.search() 的返回值做判断:

>>> if grps:...     raw[:grps.start()].strip()...'Toy Story'

3. 切分文本

import rere.compile('\\W*').split(sentences)
  • (1)\W:非字符
  • (2)\\W:第一个斜线表示转义;

我们可以再加一些额外的判断逻辑(或叫断言,predicate)以屏蔽那些非单词。

[word.lower() for word in re.compile('\\W*').split(sentences) if len(word) > 2 and len(word) < 20]

4. re.findall 指定长度切分

>> s = 'abcdef'>> re.findall('.{3}', s)['abc', 'def']

当要切分的对象其长度不满足于切片的倍数时:

>> s = 'abcdefgh'>> re.findall('.{3}', s) ['abc', 'def']

将会把末尾的部分舍去;

0 0
原创粉丝点击