由於業務需要,要提取指定字符串的關鍵信息。具體要求是從一個字符串中提取<>裏面的內容。
於是想到利用Python 中的正則實現。
輸入:
我要聽<樑博>的<男孩>
輸出:
樑博 男孩
Python 實現:
#coding:utf8
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
template = "我要聽<歌手名>的<歌曲名>"
def subString(template):
rule = r'<(.*?)>' # 正則規則
slotList = re.findall(rule, template)
return slotList
slotList = subString(template)
for slot in slotList:
print slot