Python中提取指定字符串

来源:互联网 发布:淘宝助手模板 编辑:程序博客网 时间:2024/06/05 08:31

Python中提取指定字符串,从一个字符串中提取<>里面的内容,整理了两种实现方式,后续有更多的实现方式继续更新
代码如下:

#coding:utf8import reimport sysreload(sys)sys.setdefaultencoding('utf8')#!/usr/bin/pythontemplate = "我要<歌手名>的<歌曲名>"def subString1(template):    copy = False    finished = False    slotList = []    str = ""    for s in template:        if s=='<':            copy = True        elif s=='>':            copy = False            finished = True        elif copy:            str = str+s        if finished:            slotList.append(str)            str = ""            finished = False    return slotListdef subString2(template):    rule = r'<(.*?)>'    slotList = re.findall(rule, template)    return slotListslotList = subString1(template)for slot in slotList:    print slotslotList = subString2(template)for slot in slotList:    print slot
0 0
原创粉丝点击