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
- Python 基础 —— re:正则表达
- Python--正则表达模块re
- Python--正则表达模块re
- python正则表达式——re模块
- Python——正则RE之flags
- python正则表达式——re模块
- Python正则表达式—re模块接口
- Python正则表达式学习(1)——re.sub()基础
- Python基础学习之re正则表达式
- python中re模块基础用法(正则)
- Python模块学习——re正则表达式模块
- Python之re模块 —— 正则表达式操作
- 正则表达式 (re包)——python(快餐)
- [Python标准库]re——正则表达式[一]
- [Python标准库]re——正则表达式[二]
- [Python标准库]re——正则表达式[三]
- [Python标准库]re——正则表达式[四]
- [Python标准库]re——正则表达式[五]
- labwindows远程数据库操作
- Matlab读取纯文本光谱文件
- 【数据结构与算法】十五
- Ubuntu+Apache+PHP+Mysql环境搭建
- 命名不能用的数据库关键字
- Python 基础 —— re:正则表达
- jdk环境变量含义极其配置
- 【poj 3258】River Hopscotch 中文题意&题解&代码
- 每天laravel-20160624|RateLimiter
- XML解析
- 排序的稳定性
- bzoj 4383: [POI2015]Pustynia 线段树优化建图
- BZOJ_P1934 [Shoi2007]Vote 善意的投票(最小割)
- [spoj244]Transposing is Even More Fun 解题报告