[项目实训]Python正则表达式和Re库

来源:互联网 发布:高胜算交易策略 知乎 编辑:程序博客网 时间:2024/06/05 13:23

正则表达式

定义:正则表达式是用来简洁表达一组字符串的表达式 



例:匹配IP地址的正则表达式

IP地址字符串形式的正则表达式(IP地址分4段,每段0255)\d+.\d+.\d+.\d+\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}

精确写法 

099:[19]?\d

100199:1\d{2}

200249:2[04]\d

250255:25[05]


(([19]?\d|1\d{2}|2[04]\d|25[05]).){3}([19]?\d|1\d{2}|2[04]\d|25[05]) 

Re库

raw string类型(原生字符串类型)

re库采用raw string类型表示正则表达式,表示为:r'text'

例如: r'[19]\d{5}'r'\d{3}\d{8}|\d{4}\d{7}'

raw string是不包含对转义符再次转义的字符串 



实例:淘宝定向爬虫

import requestsimport reimport sysdef getHTMLText(url):try:r = requests.get(url,timeout=30)r .raise_for_status()r.encoding = r.apparent_encodingreturn r.textexcept:return ""def parsePage(ilt,html):try:plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)for i in range(len(plt)):price = eval(plt[i].split(':')[1])title = eval(tlt[i].split(':')[1])ilt.append([price,title])except:print("")def printGoodsList(ilt):tplt = "{:4}\t{:8}\t{:16}"print(tplt.format("序号","价格","商品名称"))count = 0for g in ilt:count = count + 1print(tplt.format(count,g[0],g[1]))def main():print(sys.getdefaultencoding())goods = '书包'depth = 2start_url = 'http://s.taobao.com/search?q=' + goodsinfoList = []for  i in range(depth):try:url = start_url + '&s=' + str(44*i)html = getHTMLText(url)parsePage(infoList,html)except:continueprint(len(infoList))printGoodsList(infoList)main()


0 0