python正則表達式使用實例-替換字符串HTML標籤

最近因爲需要把字符串中的html標籤替換掉,想到的是使用正則來做,因爲原來模塊是用C++碼的,所以就用的glibc的regex來做的。後來查資料發現用python來做這件事,簡單方便,而且一次性可以完成所有替換,不想用C還需要自己寫程序移動指針完成替換。不多說了上代碼,很簡單。

 #! /usr/bin/env python
    # -*- coding:gbk -*-

    """
    Notes:
        A python script that use regex to replace all the label of a html file
    """

    import os
    import sys
    import re

    if __name__ == "__main__":
        input_file = sys.argv[1]
        with open(input_file, 'r') as fp:
            for line in fp:
                line = line.rstrip()
                pattern = re.compile(r'<([^>]*)>')
                match_list = pattern.findall(line)
                for i in range(0, len(match_list)):
                    print "matched:%s" %match_list[i]
                line = pattern.sub('', line)
                print line

輸入文件

 helle<p>world</p><br/>

輸出結果

matched:p
matched:/p
matched:br/
helleworld

這裏說一下,Python的re模塊的findall函數返回的是正則模式裏面組所匹配的內容,可以方便進一步使用。

歡迎點擊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章