python中的文本(二),

來源:互聯網
上載者:User

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'),]             )






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.