1. 关于split分割函数
函数原型:
str.split(str="", num=string.count(str))
str = "this is string example....wow!!!"
print (str.split( )) # 以空格为分隔符
print (str.split('i',1)) # 以 i 为分隔符
print (str.split('w')) # 以 w 为分隔符
以上实例输出结果如下:
[‘this’, ‘is’, ‘string’, ‘example…wow!!!’]
[‘th’, ‘s is string example…wow!!!’]``
[‘this is string example…’, ‘o’, ‘!!!’]
s="helilo"+"wiorild"
print(s)
print(s.split('i')) #以i为分隔符
结果为
helilowiorild
[‘hel’, ‘low’, ‘or’, ‘ld’]
python中集合set的运算
2. ‘’'三引号的用处
- 用于注释
'''
注释
'''
- 用于处理文本中的引号显示
print """as Mom's mom says, "you are cold" """
as Mom’s mom says, “you are cold”
- 多行输入
s = '''hello
world'''
print s
hello
world
3.2 字典的赋值方法之一
shot_id = [1,2,3]
shot_zone_area = ['Right Side(R)','Left Side(L)','Left Side Center(LC)']
for key,value in zip(shot_id,shot_zone_area):
kobe_dict[key]=value
print(kobe_dict)
#结果:
{1: 'Right Side(R)', 2: 'Left Side(L)', 3: 'Left Side Center(LC)'}
4. 数据可视化
import numpy as np
import matplotlib.pyplot as plt
a = array([1, 2, 3, 4])
b=array([2,2.4,5.6,7.9])
c=array([3,6,8.0,9.5])
plt.plot(a,b,'g',b,c,'m',a,c ,'bd')
plt.show()
x=array([1,2,3,4,5,6,7,8]) #例如
y=array([3,4,5,7,9,44,67])
z=x+9
#注意:如果点数过小的话会导致画出来二次函数图像不平滑
x = np.linspace(-1, 1,66)
#从-1-----1之间等间隔采66个数.也就是说所画出来的图形是66个点连接得来的
plt.plot(x,y,‘颜色’,x,z,‘颜色’,x,y,'颜色’) # 三条曲线 x y 分别为数列或者函数
plt.plot () #是曲线、折线
plt.bar() #是条形图
plt.barh() #这是横向的条形统计图
plt.title("随便的图表") #图表的名称
"
设置坐标轴
"
import matplotlib.pyplot as plt
import numpy as np
# 绘制普通图像
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
# 设置坐标轴的取值范围
plt.xlim((-1, 1))
plt.ylim((0, 3))
# 设置坐标轴的lable
#标签里面必须添加字体变量:fontproperties='SimHei',fontsize=14。不然可能会乱码
plt.xlabel(u'这是x轴',fontproperties='SimHei',fontsize=14)
plt.ylabel(u'这是y轴',fontproperties='SimHei',fontsize=14)
# 设置x坐标轴刻度, 之前为0.25, 修改后为0.5
#也就是在坐标轴上取5个点,x轴的范围为-1到1所以取5个点之后刻度就变为0.5了
plt.xticks(np.linspace(-1, 1, 5))
plt.show()
# 获取当前的坐标轴, gca = get current axis
ax = plt.gca()
# 设置右边框和上边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 设置x坐标轴为下边框
ax.xaxis.set_ticks_position('bottom')
# 设置y坐标轴为左边框
ax.yaxis.set_ticks_position('left')
# 设置x轴, y周在(0, 0)的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor = 'green', edgecolor = 'None', alpha = 0.7))
5 .函数map(function,iterable), 其含有两个参数,第一个参数function是一个函数(填写时应该填写函数名),第二个参数是一个列表。列表中的每一个元素调用函数function,结果构成一个新的序列。 Python用lambda关键字创建匿名函数。(匿名是因为不需要以标准的方式来声明,比如说,使用def语句)
a = lambda x,y=2:x+y
>>> a(3)
5
>>> a(3,5)
8
>>> a(0)
2
mapp = map(lambda x : x ** 2 , [1,2,3,4,5])
>>> list(mapp)
[1, 4, 9, 16, 25]
mapp = map(lambda x,y,z:x+y+z,[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5])
>>> list(mapp)
[3, 6, 9, 12, 15]
mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> list(mapp)
[5, 7, 9]
这样是可以输出内容,但是只能输出一次。原因是:迭代器对象不支持重新迭代,即同一个迭代器对象不支持多次迭代。
在迭代器对象的内部,其遍历机制实际是调用其内部函数__next__()来获取容器的下一个元素,当后面没有元素时,就抛出StopIteration异常。
mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> for item in mapp:
print(item)
5
7
9
>>> for item in mapp:
print(item)
>>>
mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> listt = list(mapp)
>>> listt
[5, 7, 9]
>>> listt
[5, 7, 9]
6.。。 列表生成式
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
输出结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
也可如下
squares = [x**2 for x in range(10)]
输出结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
也可如下
这也等价于下面的方式,但列表推导式的方式更简单。
squar = map(lambda x:x**2,range(10))
可以几个参数一起迭代
复杂的
[(x,y)for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
利用if加限制条件
squares = [x for x in range(15) if x%2==0]
print(squares)
[0, 2, 4, 6, 8, 10, 12, 14]
#对列表中的每个元素应用一个函数
[abs(x) for x in vec]
[4, 2, 0, 2, 4]
[(x,x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> #元组必须用括号包围,不然就会出错
>>> [x,x**2 for x in range(6)]
SyntaxError: invalid syntax
可以包含复杂嵌套
from math import pi
>>> [str(round(pi,i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
行列式转置
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
]
>>> matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[row[j] for row in matrix]for j in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
也可以用函数
zipp = zip(*matrix)
>>> list(zipp)
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
**
7.。。文件读写
**
删除文件:
import os
os.remove('data.txt'
读写
f=open('data.txt','w')
f.write("北京时间八点整\n")
f.close()
f=open('data.txt')
data = []
for x in f:
data.append([int(num) for num in x.split()])
f.close()
data
8…class 类
用class来定义一个类。 Person(object)表示继承自object类; __init__函数用来初始化对象; self表示对象自身,类似于C Java里面this。
class Person(object):
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return self.first + ' ' + self.last
构建新对象person = Person('Mertle', 'Sedgewick', 52)
调用属性person.first
调用方法person.full_name();
9…网络数据
# _*_ coding:utf-8 _*_
import urllib2
#向指定的url地址发送请求,并返回服务器响应的类文件对象
response = urllib2.urlopen('http://www.baidu.com/')
#服务器返回的类文件对象支持python文件对象的操作方法
#read()方法就是读取文件里的全部内容,返回字符串
html = response.read()
print html
模拟浏览器访问 +(header)
# _*_ coding:utf-8 _*_
import urllib2
# User-Agent是爬虫与反爬虫的第一步
ua_headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
# 通过urllib2.Request()方法构造一个请求对象
request = urllib2.Request('http://www.baidu.com/',headers=ua_headers)
#向指定的url地址发送请求,并返回服务器响应的类文件对象
response = urllib2.urlopen(request)
# 服务器返回的类文件对象支持python文件对象的操作方法
# read()方法就是读取文件里的全部内容,返回字符串
html = response.read()
print html
Request总共三个参数,除了必须要有url参数,还有下面两个:
data(默认空):是伴随 url 提交的数据(比如要post的数据),同时 HTTP 请求将从 "GET"方式 改为 "POST"方式。
headers(默认空):是一个字典,包含了需要发送的HTTP报头的键值对。
# _*_ coding:utf-8 _*_
import urllib2
# User-Agent是爬虫与反爬虫的第一步
ua_headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
# 通过urllib2.Request()方法构造一个请求对象
request = urllib2.Request('http://www.baidu.com/',headers=ua_headers)
#向指定的url地址发送请求,并返回服务器响应的类文件对象
response = urllib2.urlopen(request)
# 服务器返回的类文件对象支持python文件对象的操作方法
# read()方法就是读取文件里的全部内容,返回字符串
html = response.read()
# 返回HTTP的响应吗,成功返回200,4服务器页面出错,5服务器问题
print response.getcode() #200
# 返回数据的实际url,防止重定向
print response.geturl() #https://www.baidu.com/
# 返回服务器响应的HTTP报头
print response.info()
# print html
随机选择user-agent、防止ip被封
# _*_ coding:utf-8 _*_
import urllib2
import random
url = 'http:/www.baidu.com/'
# 可以试User-Agent列表,也可以是代理列表
ua_list = ["Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]
# 在User-Agent列表中随机选择一个User-Agent
user_agent = random.choice(ua_list)
# 构造一个请求
request = urllib2.Request(url)
# add_header()方法添加/修改一个HTTP报头
request.add_header('User-Agent',user_agent)
#get_header()获取一个已有的HTTP报头的值,注意只能第一个字母大写,后面的要小写
print request.get_header('User-agent')
url = ‘http://m.sohu.com/?v=3&once=000025_v2tov3&_smuid =ICvXXapq5EfTpQTVq6Tpz‘
req = urllib2.Request(url)
resp = urllib2.urlopen(req)
page = resp.read()