七月在线爬虫班学习笔记(二)——Python基本语法及面向对象
第二课主要内容如下:
- 代码格式
- 基本语法
- 关键字
- 循环判断
- 函数
- 容器
- 面向对象
- 文件读写
- 多线程
- 错误处理
代码格式

syntax基本语法
a = 1234
print(a)
a = 'abcd'
print(a) try:
print(b)
except Exception as e:
print(e) a = [1, 2, 3 , 4] def func(a):
a[0] = 2 func(a)
print(a) try:
# Python 2.x 支持
print(100, 200, 300)
except Exception as e:
print(e)
1234
abcd
name 'b' is not defined
[2, 2, 3, 4]
100 200 300
condition_and_loop 循环判断
score = 80
if score > 90:
print('A')
elif score > 70:
print('B')
elif score >= 60:
print('C')
else:
print('D') total = 0
i = 1
while i <= 100:
total += i
i += 1 # 没有++i或者--i
print(total) '''
for循环只作用于容器!!!
没有这种写法:
for (i = 0; i < 100; ++i):
# TODO
上面这种循环只能用while实现
''' i = 0
while i < 3:
j = 0
while j <= 3:
if j == 2:
j += 1
continue # 又去了while j <= 3
print(i, j)
j += 1
i += 1
B
5050
0 0
0 1
0 3
1 0
1 1
1 3
2 0
2 1
2 3
func函数
def hello(who = 'world'):
print('hello %s!' % (who)) hello()
hello('sea') # f(x) = x * 5 + 100
# g(x) = x * 5; f(x) = x + 100
# => f(g(x)) = x * 5 + 100
def g(x):
return x * 5
def f(gf, x):
return gf(x) + 100
print(f(g, 100))
print(f(lambda x: x * 5, 100)) def f(gf, x, y):
return gf(x, y) + 100
print(f(lambda x, y: x * y, 100, 200)) #输出结果
hello world!
hello sea!
600
600
20100
ct_list数组
# list就是数组
li = [1, 2, 3, 4, 5]
# 遍历
for i in li:
# print(i)
pass
# 用range模拟for (i = 0; i < x; ++i)
# range(x) => [0, x - 1]
# range(x, y) => [x, y - 1]
# range(x, y, z) => [x, x + z,..., < y]
for i in range(len(li)):
# print(li[i])
pass for i in range(1, 10, 2):
print(i) #输出结果
1
3
5
7
9
# 负数索引
print(li[-1])
print(li[-2]) # 负数step的range => [x, x - z, ..., > z]
for i in range(3, -1, -1):
print(i)
#输出结果
5
4
3
2
1
0
# 添加元素
li = []
li.append(1)
li.append(2)
li.append('abc')
li.append(['d', 'e', 'f'])
print(li) # 按元素添加数组
li = [1, 2]
li_2 = [3, 4, 5]
# 我们想要[1, 2, 3, 4, 5]
# li.append(li_2) => [1, 2, [3, 4, 5]]
li.extend(li_2)
print(li) # 删除元素
li.pop() # => [1, 2, 3, 4]
print(li)
li.pop(2) # => [1, 2, 4]
print(li) #输出结果
[1, 2, 'abc', ['d', 'e', 'f']]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 4]
li = [5, 8, 7, 4, 2, 3]
li.sort()
print(li)
# lambda帮助排序
li = [[5, 2], [3, 8], [2, 11], [7, 6]]
# li.sort(key = lambda x: x[0]) # 参数名字
# 与lamda等价写法
def item_key(x):
return x[0]
li.sort(key = item_key)
print(li) #输出结果
[2, 3, 4, 5, 7, 8]
[[2, 11], [3, 8], [5, 2], [7, 6]]
ct_tuple只读数组
# 只读数组
tp = (1, 2, 3)
try:
tp[0] = 100
except Exception as e:
print(e)
ct_set没有重复元素的数组
s = set([1, 2, 2, 3, 3, 4, 5])
print(s)
s = set((2, 3, 4, 5, 6, 2, 1, 9))
print(s) #输出
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 9}
ct_dict 字典(哈希表)
# key<->value对应的hash表
di = {'k1': 'v1', 'k2': 'v2'}
di['k3'] = 'v3'
di['k4'] = 'v4' for k in di:
print(di[k]) for k, v in di.items():
print(k, v) #输出
v3
v4
v2
v1
k3 v3
k4 v4
k2 v2
k1 v1
slice数组切片
# [1, 2, 3, 4, 5]
# => [1, 2, 3]
# => [3, 4]
li = [1, 2, 3, 4, 5]
li_0_2 =li[0:3] # 0 <= ? < 3
# 等价li[:3]
print(li_0_2)
# [start, end, step] => [start, start + step, ..., < end]
# start默认是0,end默认-1,step默认1
li_last_3 = li[-1:-4:-1]
print(li_last_3) # 直接用切片反转数组
print(li[::-1])
print(li[-2::-1]) # 切片是复制
li_0_2[-1] = 100
print(li) #输出
[1, 2, 3]
[5, 4, 3]
[5, 4, 3, 2, 1]
[4, 3, 2, 1]
[1, 2, 3, 4, 5
list_string字符串与数组的关系
s = 'abcdefg'
try:
str[0] = 'x'
except Exception as e:
print(e) # 修改字符串
li = list(s)
# print(li)
li[0] = 'x'
s = ''.join(li)
print(s)
s = '-'.join(li)
print(s) # 切割
s = 'abc,def,ghi'
p1, p2, p3 = s.split(',')
print(p1, p2, p3) # 下标访问和切片
s = 'abcdefg'
print(s[0], s[-1])
print(s[2:5]) #输出
'type' object does not support item assignment
xbcdefg
x-b-c-d-e-f-g
abc def ghi
a g
cde
obj面向对象
# 用type查看对象类型
print(type([1, 2, 3, 4]))
print(type('abcd'))
print(type({1:2, 2:3})) # 用dir查看属性和方法
print(dir(list))
<class 'list'>
<class 'str'>
<class 'dict'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
class Clazz(object):
# self参考C++的this指针!
def __init__(self, x, y):
self.x = x
self.y = y # 声明成员函数的时候,第一个参数一定是self,不要忘记!
def display(self):
print(self.x, self.y) print(type(Clazz))
clz = Clazz(100, 200)
clz.display() # => display(clz) class Base:
def run(self):
print('Base::run') class Tom(Base):
def run(self):
print('Tom::run') t = Tom()
print(isinstance(t, Base))
t.run()
<class 'type'>
100 200
True
Tom::run
def run(runner):
runner.run() class R1:
def run(self):
print('R1::run') class R2:
def run(self):
print('R2::run') run(R1())
run(R2()) #输出
R1::run
R2::run
file_rw文件读写
# 打开文件操作可能失败,异常处理后不会造成资源泄露等情况
with open('text.txt', 'w') as f:
f.write('''1234
abcd
nefgh''') with open('text.txt', 'rb') as f:
print(f.read()) with open('text.txt') as f:
for line in f.readlines():
print(line.strip()) #输出
b'1234\r\n abcd\r\n nefgh'
1234
abcd
nefgh
threads多线程
import threading def thread_func(x):
# 自己加sleep和其它复杂操作看效果
print('%d\n' % (x * 100)) threads = []
for i in range(5):
threads.append(threading.Thread(target = thread_func, args = (100, ))) for thread in threads:
thread.start() for thread in threads:
thread.join() #输出
10000 10000 10000 10000 10000
error_handling错误和异常处理
# 错误处理 try:
r = 10 / 0
except ZeroDivisionError as e:
print(type(e))
print(e)
finally:
# 主要防止资源泄露(服务端。客户端一般不会资源泄露)!
print('Always come here.') #输出
<class 'ZeroDivisionError'>
division by zero
Always come here.
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
七月在线爬虫班学习笔记(二)——Python基本语法及面向对象的更多相关文章
- 七月在线爬虫班学习笔记(五)——scrapy spider的几种爬取方式
第五课主要内容有: Scrapy框架结构,组件及工作方式 单页爬取-julyedu.com 拼URL爬取-博客园 循环下页方式爬取-toscrape.com Scrapy项目相关命令-QQ新闻 1.S ...
- 七月在线爬虫班学习笔记(六)——scrapy爬虫整体示例
第六课主要内容: 爬豆瓣文本例程 douban 图片例程 douban_imgs 1.爬豆瓣文本例程 douban 目录结构 douban --douban --spiders --__init__. ...
- python学习笔记(二):python数据类型
上一篇博客写了python的入门和简单流程控制,这次写python的数据类型和各种数据类型的内置方法.一.数据类型是什么鬼?计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各 ...
- Java学习笔记二十九:一个Java面向对象的小练习
一个Java面向对象的小练习 一:项目需求与解决思路: 学习了这么长时间的面向对象,我们只是对面向对象有了一个简单的认识,我们现在来做一个小练习,这个例子可以使大家更好的掌握面向对象的特性: 1.人类 ...
- Java基础学习笔记二 Java基础语法
注释 注释用来解释和说明程序的文字,注释是不会被执行的. 单行注释 //这是一条单行注释 public int i; 多行注释 /* 这是 * 一段注释, * 它跨越了多个行 */ public vo ...
- Java基础学习笔记五 Java基础语法之面向对象
面向对象 理解什么是面向过程.面向对象 面向过程与面向对象都是我们编程中,编写程序的一种思维方式.面向过程的程序设计方式,是遇到一件事时,思考“我该怎么做”,然后一步步实现的过程.例如:公司打扫卫生( ...
- Html学习笔记(二) 简单标签
标签的重点 标签的用途 标签在浏览器中的默认样式 <body>标签: 在网页上显示的内容 <p>标签: 添加段落 <hx>标签: 添加标题 标签一共有6个,h1.h ...
- 风变编程笔记(二)-Python爬虫精进
第0关 认识爬虫 1. 浏览器的工作原理首先,我们在浏览器输入网址(也可以叫URL),然后浏览器向服务器传达了我们想访问某个网页的需求,这个过程就叫做[请求]紧接着,服务器把你想要的网站数据发送给浏 ...
- python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码
python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...
随机推荐
- matlab 入门
---恢复内容开始--- 1.cast表示将元素转化成对应的ASCII值 如cast('hellothere','uint8')输出结果为104 101 108 108 111 116 104 101 ...
- Visual Studio 2017 注册码
Visual Studio 2017(VS2017) 企业版 Enterprise 注册码:NJVYC-BMHX2-G77MM-4XJMR-6Q8QF Visual Studio 2017(VS201 ...
- Pandas 基础(16) - Holidays
这节依然是关于时间方面的知识.上一节学习了如何获取日期序列的函数, 以及通过一些基本的参数设置可以使时间序列跳过休息日等.这一节, 将要深入学习这个点, 做更自定义的设计. 通过上一节的学习, 我们知 ...
- java导出excel 浏览器直接下载或者或以文件形式导出
/** * excel表格直接下载 */ public static void exportExcelByDownload(HSSFWorkbook wb,HttpServletResponse ht ...
- winform使用log4.net
因为我最近负责的Winform项目,好多都用到了这个log4net的日志功能,开发程序对数据一般都要求做到雁过留痕,所以日志对于我们程序员是不可或缺.因此我把对log4net的使用做一个记录总结,以便 ...
- java日期和时间Date、Calendar、SimpleDateFormat
1 时间和日期 1.1 日期类Date和格式化SimpleDateFormat 日期使用过程中需要将日期Date对象转化为字符串,或者将字符串形式的日期转化为日期Date对象.可 ...
- 第 10 章 容器监控 - 079 - 监控利器 sysdig
sysdig 是一个轻量级的系统监控工具,同时它还原生支持容器. 通过 sysdig 我们可以近距离观察 linux 操作系统和容器的行为. Linux 上有很多常用的监控工具,比如 strace,t ...
- 搭建日志收集系统时使用客户端连接etcd遇到的问题
问题: 在做日志收集系统时使用到etcd,其中server端在linux上,首先安装第三方包(windows)(安装过程可能会有问题,我遇到的是连接谷歌官网请求超时,如果已经出现下面的两个文件夹并且文 ...
- opencv的一些功能代码
opencv调用摄像头 #include<opencv2/opencv.hpp> using namespace cv; void main(){ VideoCapture cap; ca ...
- [springMvc] 源码分析笔记(二)
1.SpringMvc 中核心Servlet的继承结构图 2.HttpServletBean public abstract class HttpServletBean extends HttpSer ...