math相关的函数
abs(-
22)
round(
12.212)
from math import
sqrt
sqrt(
9)
string字符串相关
name = raw_input(u
"请输入你的名字:")
x=
"ss"
y=
"ss"
x+y
lower 返回字符串的小写字母版 replace 替换元素
split 将字符串分割成序列 .split("")括号里面可以用正则表达式
strip 去除两侧空格的字符串
num = [
1,
2,
3,
4,
5,
6,
7,
8]
max(
num)返回最大值
len 返回元素数量
max min 返回序列中最大最小元素
a=
num[
0:
4]
print(
num[
0:
8:
2])
列表和元组的区别在于 列表可以修改 元组不能修改
list相关操作
list del 删除元素
list 追加新元素 append count 统计某个元素在list 中出现的次数
extend 在列表末尾一次最近另外一个序列的多个值
index 找出某个值的第一个匹配项的索引位置 index(
'')
insert 将对象插入列表 insert (
num,
'')
remove 删除列表中某个值的第一个匹配项
resverse 元素反序列
sort 排序
元组
asa=(
1,
2,
3,
4) 不可修改
tuple([
1,
2,
3,
4])
字典
a = {
'':
'',
'':
'' } d=dict(name=
'',age=
'')
d= dict(name=
'ss',age=
'22')
clear 清除字典所有项
get 访问字典项 has_key 是否存在给出的键 在python3
.0中 不存在这个函数
items 把所有的字典项以列表方式返回 iteritems 返回一个迭代器对象
pop 对应的键值 然后把键值对从字典中移除
update 利用一个字典项更新另外一个字典
values 以列表的形式返回字典中的值
条件语句
if else elif is is
not in not in
列表递推式 [x*x
for x
in rang(
10)] 用其他列表创建一个新的列表
pass 什么都没有发生 del 删除不在使用的对象
异常处理
ry except 捕捉对象
try except ( error),e: print e python
3 会写成
as e
捕捉全部对象 except Exception , e:
文件操作
open 函数打开文件 模式参数常用值 r 读 w 写
a 追加 b 二进制模式
文件读 readline
def ostest():
import os
os.renames(
'oldpath',
'newpath')
os.remove(
'path')
os.mkdir(
'pathname')
os.mkdirs(
'')
os.path.getsize(
'path')
def filetest():
f =
open(
'filename',
'w')
f.
write(
"")
f.
close()
f =
open(
'filename',
'r')
f.
read()
f.readline()
for line in f.readlines():
print(
line)
f.readlines()
f.
seek(
num)
f =
open(
'filename',
'a')
aa=f.
read()
f.
close()
des=f.
open(
'path')
des.
write(aa)
des.
close()
filejpg=
open(
'path.jpg',
'rb')
co=filejpg.
read()
filejpg.
close()
destfile=
open(
'path.jpg',
'wb')
destfile.
write(co)
destfile.
close()
安装MySQL
打开数据库连接 db=mysqldb. connect (
'地址',
'用户',
'密码',
'数据库')
cur =db.coursor()
执行命令 cur.execute(
'')
data=cur.fetchone() 提取结果
创建数据库
sql=
"creat database xxx" "creat tabele (id int ...." 'inster into table (name,age) values()'','''
cur.execute(sql)执行语句
db.commit 提交
打印数据库中的所有数据
sql=
"select * from table"
cur.execute(sql)
result =cur.fetchall()
for row
in result :
print row
python网络爬虫
import urllib2
url=
"https://www.baidu.com/"
f=urllib2.urlopen(url)
s=f.
read()
print(s)
request=urllib2.Request(url)
resp=urllib2.urlopen(request)
ss=resp.
read()
request=urllib2.Request(url,headers=
'')
response=urllib2.urlopen(request)
response.
read()
关于网络爬虫 现在大多数都是使用request而不是使用urlib,在网络爬虫的时,使用beautifulgroup是一个很好用的工具。当然在爬去数据的时候,最好是使用线程,并且每次爬去最好休眠一定时间,也可以使用urlib2 设置头处理,伪装成客户端。对于爬去的数据可以保存在本地,但是最好的方式是保存在数据库中,mongodb是一个比较合适的数据库
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。