python正文(两)
2015-10-18 19:34
746 查看
在本文中,我读了记录和总结《Python标准库》一本书,本节课文的学习和理解。
事实上,在Python于,使用一些方法这段文字是一回事,尤其是经常使用。在一般情况下,会用String这样的类,应考虑Python个标准类了。
1.3.6 用组解析匹配
match.groups()会依照表达式中与字符串匹配的组的顺序返回一个字符串序列。
使用group()能够得到某个组的匹配。
Python对基本分组的语法进行了拓展,添加了命名组(named group)。通过名字来指示组。方便能够更easy的改动模式,而不必同一时候改动使用了该匹配结果的代码。
语法:(?
P<name>pattern)
使用groupdict()能够获取一个字典,它将组名映射到匹配的子串。
事实上,在Python于,使用一些方法这段文字是一回事,尤其是经常使用。在一般情况下,会用String这样的类,应考虑Python个标准类了。
1.3.6 用组解析匹配
match.groups()会依照表达式中与字符串匹配的组的顺序返回一个字符串序列。
使用group()能够得到某个组的匹配。
#组解析 text='This is a text -- with punctuation.' print 'Input text: ', text regex=re.compile(r'(\bt\w+)\W+(\w+)') print 'pattern: ', regex.pattern match=regex.search(text) print 'Entire match: ',match.group(0) print 'Word starting with t: ',match.group(1) print 'Word after t word: ',match.group(2)
Python对基本分组的语法进行了拓展,添加了命名组(named group)。通过名字来指示组。方便能够更easy的改动模式,而不必同一时候改动使用了该匹配结果的代码。
语法:(?
P<name>pattern)
#命名组 print '-'*30 for pattern in [r'^(? P<first_word>\w+)', r'(?P<last_word>\w+)\S*$', r'(? P<t_word>\bt\w+)\W+(?P<other_word>\w+)', r'(?P<ends_with_t>\w+t)\b' ]: regex=re.compile(pattern) match=regex.search(text) print 'Matching "%s"' % pattern print ' ',match.groups() print ' ',match.groupdict() print '\n'
使用groupdict()能够获取一个字典,它将组名映射到匹配的子串。
#更新后的test_pattern() print '-'*30 def test_pattern(text, patterns=[]): """ Given the source text and a list of patters, look for matches for each pattern within the text and print them to stdout. """ #look for each pattern in the text and print the results for pattern, desc in patterns: print 'pattern %r (%s) \n' %(pattern, desc) print '%r' % text for match in re.finditer(pattern,text): s=match.start() e=match.end() prefix=' '*(s) print ' %s%r%s' % (prefix,text[s:e],' '*(len(text)-e)) print match.groups() if match.groupdict(): print '%s%s'%(' '*(len(text)-s),match.groupdict()) print return test_pattern( 'abbaabbba', [ (r'a((a*)(b*))','a followed by 0-n a and 0-n b'),] )
相关文章推荐
- 机器学习 & python k-近邻算法处理手写识别系统
- 在windows上终止 subprocess 进程 (Python recipe)
- windows下python subprocess.Popen执行adb 命令进程无法终止
- python os.listdir / os.mkdir / os.rmdir 和 os.getcwd函数
- <LeetCode><Easy> 111 Minimum Depth of Binary Tree
- Python中的编码
- 廖雪峰Python教程学习笔记
- python IDLE入门
- raw_input() 与 input() __ Python
- Ubuntu14.04下Python3.4启动IDLE
- Python2.7 语言简介
- Python采用struct处理二进制
- <PY> Python Zen
- python学习笔记之调用eval函数出现invalid syntax错误问题
- 在arcgis使用python脚本进行字段计算时是如何解决中文问题的
- 机器学习 & python 使用k-近邻算法改进约会网站的配对效果
- Python future模块
- python常用类型的内置函数列表
- mac下python实现vmstat
- python中处理中文