python中的文本(二),
本文主要記錄和總結本人在閱讀《Python標準庫》一書,文本這一章節的學習和理解。
其實在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)。通過名字來指示組,方便可以更容易的修改模式,而不必同時修改使用了該匹配結果的代碼。
文法:(?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'),] )