Python十大装逼语法
https://blog.csdn.net/xufive/article/details/102856921
1. for...else...语句
2. * 列表参数 ** 键值对参数
3. x = "y小于0" if y<0 else "y不小于0" 三元表达式
4. with...as... 例如 with open("test.txt","w",encoding="utf-8") as f with 语句适合一些事先需要准备,事后需要处理的任务
5. 列表推导式,数组中嵌循环 result = [i*i for i in a]
6. 切片,负数索引
7. lambda函数,匿名函数。(lambda x,y: x+y)(3,4) 参数需要括号括起来
8. yield
9. 装饰器
10. 巧用断言assert
def i_want_to_sleep(delay):
assert(isinstance(delay, (int,float))), '函数参数必须为整数或浮点数'
#判断assert,为真,则忽略。不为真,则报错"AssertionError: 函数参数必须为整数或浮点数"
yield 以及生成器和迭代器
但是如果计算1亿以内的所有整数的平方,这个函数的内存开销会非常大,这是 yield 就可以大显身手了:
>>> def get_square(n):
for i in range(n):
yield(pow(i,2))
>>> a = get_square(5)
>>> for i in a:
print(i, end=', ')
0, 1, 4, 9, 16,
装饰器
import time
def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print('耗时%0.3f'%(t1-t0,))
return wrapper
@timer
def do_something(delay):
print('函数do_something开始')
time.sleep(delay)
print('函数do_something结束')
do_something(3)
函数do_something开始
函数do_something结束
耗时3.077
机器学习项目流程
1.目标定义
a任务理解。
b.指标确定。
c.实际问题抽象为数学问题
2.获取数据
a.爬虫或第三方数据源
b.数据质量把控(数据完整无缺,各项指标齐全),
3.数据清洗.
a.重复数据
b.缺失值.
c.异常值
d.数据类型转换,
4.数据变换.
a.属性变换
b.数据集成
c.归-化
5.探索性数据分析
a.变量识别。
b.单变量分析.
c.双变量分析,
d.相关系数、
6.模型构建,
a.回归。
b.分类
c.聚类
d.推荐,
7.模型评测,
a.多模型对比。
b.模型优化,
8.模型部署
爬虫
1.导包 import requests/pip install requests
2.配置 网址、请求头
3.获取 requests.get() 方法获取html,获取后可先保存文件,避免多次访问
4.解析 加载第三方的包来解析html的标签,取得网址、图片等。导入beautifulsoup4
5.选择器筛选 先找标签元素,然后遍历,再找属性值
爬虫选取元素 :
先找到你想爬取的元素的能唯一标识的div(不一定是div,只要是能唯一确定),
通过doc.select(’.唯一标识的class名 .唯一标识的class名 标签名’)
例:
<div class="episodeIntro-line">
<p class="episodeIntro-area" itemprop="contentLocation">
<em>地区:</em>
<a href="//www.iqiyi.com/lib/dianshiju/%2C其它%2C_10_1.html" data- pb="&c1=2" rseat="708111_qwys_diqu" target="blank" itemprop="contentLocation"> 其他</a>
</p>
<p class="episodeIntro-time">
<em>时间:</em>
<span>2015</span>
</p>
</div>
获取时间2015:
1.doc.select('.episodeIntro-line .episodeIntro-time span').text
2.doc.select('.episodeIntro-time span').text
反爬操作
1.同一用户频繁访问
cookie中有信息,绕过登录时,频繁访问被监控
使用程序登录页面,产生cookie。然后使用这个cookie绕过登录
解决方法:删除cookie(保存在客户端)
2.同一地址频繁访问
换ip,使用ip代理,随机使用代理池中的ip
3.同一引擎频繁访问
同样的user-agent,一些网站会收集网络上最常见的UA组合,时刻记录自身网站被访问的最多的UA
4.ip封锁
使用ip代理,
5.用户封锁
Python爬虫框架
scrapy入门
scrapy模块
scrapy engine
scheduler
downloader
spider
itempipline
深度爬虫
限制:只怕哪一类的网站,dangdang.com
1.安装:
1.visual c++ 14.0
2.lxml
3.pywin32
4.pyOpenSSL
5.pip install scrapy
2.scrapy的结构
1.要爬取的Url来了,引擎会把url加入到调度器(scheduler调度器)
2.调度器又将url给到引擎 (scrapy engine引擎)
3.引擎再给到中间件(Downloader Middlewares)再给到下载器 (downloader下载器,拿到html)
4.downloader下载器将html响应给引擎
5.引擎将html给到中间件(Spider Middlewares)再给到Spider (Spider拿到items)
6.Spider响应items到引擎
7.引擎将items直接给到itemspipline处理,进行数据清理/持久化
深度爬取中Spider会将可爬取网址给引擎,再提交给Scheduler继续爬取
3.css解析器/XPath
创建scrapy项目
全程在cmd中操作,需要配置python环境
scrapy startproject dangdangSpider #scrapy会自动生成一个项目
在spiders文件夹中新建dangdangSpider.py
#dangdangSpider.py
#encoding:utf-8
import scrapy
class DangdangSpider(scrapy.Spider):
#必须要有name,start_urls,parse()
name = "ddspider"
start_urls = [""]
#指明深度爬虫的时候只能访问的连接限制
allowed_domains = ['dangdang.com']
def parse(self,response):
#xpath
#nodename节点
#如果是title属性,@title;如果是标签值 text()
#name = response.xpath(".//*[@class='name']/a/text()")[0].extract()
books = response.xpath(".//*[@class='bigimg']/li")
for book in books:
name = book.xpath(".//*[@class='name']/a/@title")[0].extract()
price = book.xpath(".//*[@class='price']/text()")[0].extract()
print(name + ':' + price)
网址测试
scrapy shell 网址 #没报错则成功
response.xpath(".//*[@class=‘name’]/a/text()")[0].extract() #extract()从列表提取出来
scrapy crawl ddspider #设置的name属性的值,先去当前项目的路径
#.//*[@class=‘name’]/a/text()
. 表示id是当前节点,相当于body标签
// 表示所有从属于这个节点的元素
[@class=‘name’] @表示找到,class名字为’name’的元素
/a 这个节点的a子节点
/text 表示这个变迁的值
@title 表示这个属性的值
.extract() 拿到这个选择器的data的值
```python
import re
import requests
from bs4 import BeautifulSoup
```
```python
init_url = 'https://so.iqiyi.com/so/q_1/'
```
```python
response = requests.get(init_url)
content = response.text
```
```python
doc = BeautifulSoup(content,'html.parser')
```
```python
# 获取所有的搜索结果
links = doc.select('.result-right h3 a')
video_links = []
for link in links:
video_links.append(link.get('href'))
```
http://www.iqiyi.com/a_19rrht20yt.html
http://www.iqiyi.com/lib/m_213143214.html?src=search
http://www.iqiyi.com/lib/m_210387414.html?src=search
http://so.iqiyi.com/so/q_%E5%A5%BD%E7%9C%8B%E7%9A%84%E9%AD%94%E5%B9%BB%E5%8A%A8%E6%BC%AB?source=grcm
https://live.iqiyi.com/s/19rs77jdvz.html
https://live.iqiyi.com/s/19rs77jgeb.html
http://www.iqiyi.com/lib/m_212394614.html?src=search
http://www.iqiyi.com/lib/m_201732314.html?src=search
http://www.iqiyi.com/lib/m_206855814.html?src=search
http://www.iqiyi.com/lib/m_214243014.html?src=search
http://www.iqiyi.com/a_19rrh0ruzh.html
http://www.iqiyi.com/lib/m_200267414.html?src=search
http://www.iqiyi.com/lib/m_205002414.html?src=search
http://so.iqiyi.com/so/q_%E5%80%BC%E5%BE%97%E4%B8%80%E7%9C%8B%E7%9A%84%E7%9C%9F%E4%BA%BA%E5%8A%A8%E6%BC%AB?source=grcm
http://www.iqiyi.com/lib/m_222312214.html?src=search
http://www.iqiyi.com/lib/m_208332314.html?src=search
http://www.iqiyi.com/v_19rqxtk6h8.html
http://www.iqiyi.com/a_19rrhx6ypx.html
http://so.iqiyi.com/so/q_%E7%BD%91%E5%89%A7%E6%8E%A8%E8%8D%90%EF%BC%8C%E4%B8%8D%E5%89%A7%E8%8D%92?source=grcm
http://www.iqiyi.com/a_19rrhzom39.html
http://www.iqiyi.com/v_19rsc1x0ng.html
http://www.iqiyi.com/playlist557409602.html
```python
# 采集电影信息
content = requests.get(video_links[1]).text
doc = BeautifulSoup(content,'html.parser')
print('上映时间为 : ',doc.select(".episodeIntro-line .episodeIntro-time span")[0].text)
print(doc.select(".info-intro h1 a")[0].get("title"))
```
上映时间为 : 2015
重水战争
```python
infos = []
for i in range(len(video_links)):
try :
info = {}
content = requests.get(video_links[i]).text
doc = BeautifulSoup(content,'html.parser')
info['名称'] = doc.select(".info-intro h1 a")[0].get("title")
info['上映时间'] = doc.select(".episodeIntro-line .episodeIntro-time span")[0].text
infos.append(info)
except :
continue
```
```python
infos
```
[{'上映时间': '2015', '名称': '重水战争'},
{'上映时间': '2016', '名称': '新葫芦兄弟第1季 上篇'},
{'上映时间': '2016', '名称': '新葫芦兄弟第1季'},
{'上映时间': '2013', '名称': '疯狂的兔子1'},
{'上映时间': '2013', '名称': '爆笑虫子第1季'},
{'上映时间': '2017', '名称': '旋风战车队'},
{'上映时间': '2012', '名称': '芭比之梦想豪宅'},
{'上映时间': '2007', '名称': '奥特银河大怪兽之战'},
{'上映时间': '2009', '名称': '顶级生活第1季'},
{'上映时间': '2017', '名称': '汪汪队立大功第1季'}]
```python
import pandas as pd
```
```python
df = pd.DataFrame(infos)
```
```python
df
```
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>上映时间</th>
<th>名称</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>2015</td>
<td>重水战争</td>
</tr>
<tr>
<th>1</th>
<td>2016</td>
<td>新葫芦兄弟第1季 上篇</td>
</tr>
<tr>
<th>2</th>
<td>2016</td>
<td>新葫芦兄弟第1季</td>
</tr>
<tr>
<th>3</th>
<td>2013</td>
<td>疯狂的兔子1</td>
</tr>
<tr>
<th>4</th>
<td>2013</td>
<td>爆笑虫子第1季</td>
</tr>
<tr>
<th>5</th>
<td>2017</td>
<td>旋风战车队</td>
</tr>
<tr>
<th>6</th>
<td>2012</td>
<td>芭比之梦想豪宅</td>
</tr>
<tr>
<th>7</th>
<td>2007</td>
<td>奥特银河大怪兽之战</td>
</tr>
<tr>
<th>8</th>
<td>2009</td>
<td>顶级生活第1季</td>
</tr>
<tr>
<th>9</th>
<td>2017</td>
<td>汪汪队立大功第1季</td>
</tr>
</tbody>
</table>
</div>
```python
```
```python
import numpy as np
```
```python
# 创建数组
np_array = np.array([1,2,3])
```
```python
arr = [1,2,3]
print(type(np_array))
```
<class 'numpy.ndarray'>
```python
# 创建矩阵
matrix = np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
```
```python
# 查看矩阵的结构
matrix.shape
```
(3, 3)
```python
# 查看矩阵的维度
matrix.ndim
```
2
```python
matrix[0][0]
```
1
```python
# 向量操作
np_arr1 = np.array([1,2,3])
np_arr2 = np.array([4,5,6])
arr1 = [1,2,3]
arr2 = [4,5,6]
```
```python
(np_arr1+np_arr2).T
```
array([5, 7, 9])
```python
# 点乘 , 两种方法
np_arr1.dot(np_arr2)
np.dot(np_arr1 , np_arr2)
```
32
```python
# 矩阵操作
matrix = np.arange(1,10)
print(matrix)
```
[1 2 3 4 5 6 7 8 9]
```python
matrix = matrix.reshape(3,3)
```
```python
# 逆矩阵
np.linalg.det(matrix)
```
-9.5161973539299405e-16
```python
```
```python
import matplotlib.pyplot as plt
```
```python
x = np.linspace(-10,10,1000)
cos_y = np.cos(x)
sin_y = np.sin(x)
```
```python
plt.plot(x,cos_y,color = 'r',label = 'cos_y')
plt.plot(x,sin_y,color = 'b',label = 'sin_y')
plt.show()
```

```python
```
```python
df = pd.DataFrame([
[1001,'a',11],
[1001,'a',11],
[1001,'a',11],
])
```
```python
df[0]
```
0 1001
1 1001
2 1001
Name: 0, dtype: int64
```python
```