[项目实训]Python正则表达式和Re库
来源:互联网 发布:高胜算交易策略 知乎 编辑:程序博客网 时间:2024/06/05 13:23
正则表达式
定义:正则表达式是用来简洁表达一组字符串的表达式
例:匹配IP地址的正则表达式
IP地址字符串形式的正则表达式(IP地址分4段,每段0‐255)\d+.\d+.\d+.\d+或\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}
精确写法
0‐99:[1‐9]?\d
100‐199:1\d{2}
200‐249:2[0‐4]\d
250‐255:25[0‐5]
(([1‐9]?\d|1\d{2}|2[0‐4]\d|25[0‐5]).){3}([1‐9]?\d|1\d{2}|2[0‐4]\d|25[0‐5])
raw string类型(原生字符串类型)
re库采用raw string类型表示正则表达式,表示为:r'text'
例如: r'[1‐9]\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
- [项目实训]Python正则表达式和Re库
- 正则表达式和python的re模块
- 正则表达式,和python re模块
- Python正则表达式和re模块
- Python中的re模块和正则表达式
- 正则表达式和python re模块
- python正则表达式和re模块
- Python 正则表达式 re
- python-re【正则表达式】
- python re 正则表达式
- Python re正则表达式
- python 正则表达式 re
- Python正则表达式(re)
- re 正则表达式 Python
- python正则表达式(re)
- python re正则表达式
- python正则表达式re
- python正则表达式re
- P3673 小清新计数题
- 技能终将过时,而能力与时俱进
- PAT_1038. Recover the Smallest Number
- Linux基础笔记1
- openslide安装教程
- [项目实训]Python正则表达式和Re库
- StringBuffer类操作字符串
- LDA主题模型、Word2Vec
- 动态规划5
- 数据库中的范式
- [Leetcode] #221 Maximal Square (DP)
- 上传文件到github
- 编写python爬虫 获取中华英才网全网工资数据
- 第一周(2):myflag开发细化