现在的位置: 首页 > 综合 > 正文

python中的文本(二)

2017年02月01日 ⁄ 综合 ⁄ 共 1459字 ⁄ 字号 评论关闭

 本文主要记录和总结本人在阅读《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'),]
             )

抱歉!评论已关闭.