小瓜的python自学记录

python基础知识

1.1认识python

  • python解释型语言,不需要编译直接运行,不同于java->运行时间较长
  • 面向对象,同java(封装、继承、多态)
  • 开源免费,脚本语言(解释型语言)
  • 学习python3,不向后兼容

1.2变量及类型

  • 变量可以是任意数据类型
  • 变量名必须是大小写英文、数字、下划线_的组合且不能以数字开头
  • 定义变量不需要指定变量类型,直接指定可以。字符串变量用双引号赋值

1.3关键字和标识符

  • 不能定义与关键字相同名字的标识符或变量

1.4格式化输出

# 格式化输出
age=18
print("我的年纪是:%d岁"%age)
# %作为占位符,d表示整数,最后%age表示占位置的地方需要输出的内容是什么
print("我的姓名是:%s,我的国籍是:%s"%("小瓜","中国"))
  • %s输出字符串 %d输出int类型的整数
    -我的年纪是:18岁 我的姓名是:小瓜,我的国籍是:中国
print("aaa","bbb","ccc")#默认用空格分割
print("www","baidu","com",sep=".")#用点来分割前面的字符
print("hello",end="")#后面紧接着下一条输出语句
print("world",end="\t")#打印一个tab键
print("python",end="\n")#打印回车
print("end")#打印回车

输出结果
1.5 强制类型转换

password = input("请输入密码")#password类型为字符串String类型
print("您刚刚输入的密码是:",password)
print(type(password))
a=int (password)#强制类型转换
print(type(a))

输出:

请输入密码13
您刚刚输入的密码是: 13
<class 'str'>#String类型
<class 'int'>#int类型

2、 判断语句和循环语句

  • 条件判断
    python指定任何非0和非空值为true,0或none为false
    if else elif
    • 要注意缩进,python尽量减少符号,使用格式来表达程序的范围->尽量使用tab而不用空格。

      • else中嵌套if语句

        score = 87
        if score>=90 and score<=100:
            print("本次考试等级为A")
        else :
            if score>=80 and score<=90:
                print("本次考试等级为B")
            else:
                print("本次考试等级为E")
        
        • 使用elif语句
        if score>=90 and score<=100:
            print("本次考试等级为A")
        elif score>=80 and score<90:
            print("本次考试等级为B")
        elif score>=70 and score<80:
            print("本次考试等级为C")
        else :
            print("本次考试等级为E")
        #不一定要用else结束,同Java;else可以和elif一起使用
        
        • 缩进展示
        xingbie = 1 #1boy
        danshen = 1 #1single
        
        if xingbie == 1:
            print("boy")
            if danshen == 1:
                print("single")
            else:
                print("not single")
        else:
            print("girl")
            if danshen == 1:
                print("single")
            else :
                print("not single")
        
        • 输出
        boy
        single
        
  • 循环语句
    1. for循环
    	#从0开始到4,每次加一
    	for i in range(5):
    	    print(i)
    	#输出:0 1 2 3 4
    	
    	#for(int i=0;i<10;i+=3)
    	for i in range(0,10,3):
    	    print(i)
    	#输出:0 3 6 9
    	
    	for i in range(-10,-100,-30):
    	    print(i)
    	#输出:-10 -40 -70
    	```
    
    

3、 字符串、列表、元组、字典
python的核心数据类型:

  • String(字符串)
    1. python中字符串可以使用单引号、双引号和三引号

    word = '字符串'
    sentence = "这是一个句子"
    paragraph = """
    这是一个段落
    可以有多行组成
    """
    
    print(word)
    print(sentence)
    print(paragraph)
    
  • 使用\转义特殊字符

    	#单引号和双引号的不同之处
    	#my_str1 = "i'm a student"
    	#my_str1 = 'i'm a student'#报错
    	my_str1 = 'i\'m a student'#\转义字符,显示特殊字符本来的含义
    	print(my_str1)
    	
    	my_str2 = 'jason said"i like you"'#单引号中双引号不用转义字符
    	my_str2 = "jason said\"i like you\""#双引号中的双引号需要转义字符
    	print(my_str2)
    	```
    	
    	输出:
    			```
    			i'm a student
    			jason said"i like you"
    			```
    
  • python3源码文件默认以UTF-8编码,所有的字符串都是Unicode字符串

  • 支持字符串拼接、截取等多种运算

    str = "chengdu"
    print(str)#chengdu
    print(str[4])#g
    print(str[0:6])#chengd直接当成数组来打印=substring(0,6)
    print(str[1:7:2])#hnd[起始位置:结束位置:步进值]
    print(str[:5])#cheng
    print(str[5:])#du
    print(str+"您好")#chengdu您好
    print((str+"\t") * 3)#chengdu	chengdu	chengdu
    print("hello\nchengdu")#hello换行chengdu\n转义字符
    print(r"hello\nchengdu")#hello\nchengdu开头加r后面所有的斜杠不进行转义直接输出
    
  • 列表(数组)

    1. 列表可以完成大多数集合类的数据结构实现。
    2. 列表中的元素的类型可以不相同,支持数字、字符串甚至可以包含列表(嵌套)
    3. 列表索引值以0为开始值,-1为从末尾的开始位置
    4. 可以使用+操作符进行拼接,*表示重复
  • 元组(Tuple)

    1. 元组写在小括号中
    2. 无法进行元组内的增删改查操作
  • 字典(dict)

    1. 储存键-值,无序的对象集合
    2. 同一个字典中,键(key)必须是唯一的
    3. 键必须使用不可变更数值类型
  • conclusion
    在这里插入图片描述

4、 函数

  • 函数定义
#函数的定义
def printinfo():
    print("-------------")
    print("人生苦短")
    print("-------------")

#函数的调用
printinfo()
  • 带参数的函数定义
#带参数的函数定义
def add2num(a,b):
    c = a+b
    print(c)

add2num(11,22)
  • 带返回值的函数定义
#带返回值的函数
def add2num(a,b):
    return a+b
c = add2num(11,22)
print(c)
  • 返回多个值的函数定义
#返回多个值的函数定义
def divid(a,b):
    c = a//b
    y = a%b
    return c,y      #不用定义返回值类型

sh,yu = divid(5,2)  #需要使用多个返回值来保存内容
print("商为:%d,余数为:%d"%(sh,yu))
  • 局部变量&全局变量
  1. 局部变量只在函数内部有定义
  2. 当有同名的局部变量和全局变量时,函数内部默认对局部变量进行操作
a = 100#全局变量
def test():
    print(a)
def test1():
    a = 300#局部变量
    print("test1-------:a=:%d"%a)#变量名相同时局部变量>全局变量

test()
test1()
  1. global可以使函数内部默认对全局变量进行操作
#在函数中修改全局变量
a = 100#全局变量
def test():
    print("a=%d"%a)
def test1():
    global a#此时函数中会默认对全局变量进行修改
    a = a+10
    print("a=%d"%a)#变量名相同时局部变量>全局变量

test()
test1()

5、 文件操作
文件访问模式

  • 文件的打开和关闭
  1. 打开文件
#打开文件
f = open("test.txt","w")
  1. 关闭文件
#关闭文件
f.close()  
  • 文件的读取和写入
  1. 文件的写入
f.write("hello world,I am here!")#将字符串写入文件中
  1. 文件的读取
    按字节读取文件
content = f.read(5)#读文件
content = f.read(10)#接着上次结束的位置往下读(文件指针在开始时定位在上一次结束的位置)

直接读取整个文件

content = f.readlines()#整个文件,读取成一个列表

按行读取文件

i = 1
for temp in content: 
    print("第%d行,内容为%s"%(i,temp))
    i+=1

or

content = f.readline()#一次读一行
  • os模块文件操作
import os#文件操作模块os
os.rename("test.txt","test1.txt")#重命名

6、 错误与异常

  1. 异常:发生的可以预料且希望不印象程序正常执行的错误
print("----test1-----")#成功执行
f = open("123.txt","r")#报错:用只读模式打开了不存在的文件
print("----test2-----")#执行失败
  1. 异常捕获
try:
    print("----test1-----")#成功执行
    f = open("123.txt","r")#不报错
    print("----test2-----")#执行失败
except IOError:
    pass        #出现IOError不报错

输出产生错误

try:
    print(num)
except NameError:   #异常类型需要判断正确
    print("产生错误")#输出:产生错误
try:
    print("0")#打印0
    f = open("test1.txt","r")
    print("1")#打印1
    print(num)
    print("2")#不打印2
except (NameError,IOError):   #将可能产生的所有异常类型都放到except中
    print("产生错误")#输出:产生错误
  1. 获取错误描述
try:
    print("0")#打印0
    f = open("test1.txt","r")
    print("1")#打印1
    print(num)
    print("2")#不打印2
#except (NameError,IOError) as result:   将可能产生的所有异常类型都放到except中
#不写具体错误类型:
except Exception as result:#Exception可以承接任何异常(是所有异常的父类)
    print("产生错误")#输出:产生错误
    print(result)#输出:错误类型(name 'num' is not defined)

4.try catch嵌套-文件处理和finally的使用

import time

try:
    f = open("test1.txt","r")#局部变量
    #这里发生异常直接跳到except,不进入嵌套的try,即不执行嵌套try中的finally

    try:#不管是否异常都会执行finally中的语句
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)#休眠2s
            print(content)
    finally:
        f.close()
        print("文件关闭")

except Exception as result:
    print("发生异常")
    print(result)
'''
finally:#不管是否有错误,程序最后一步都执行finally语句
    f.close()#全局变量
    print("程序执行完毕=文件关闭")
'''   

python爬虫

  • 爬取网页
    主要使用的包:urllib
    1. 获取一个get请求操作
#获取一个get请求
#用于储存cookie(被认为是爬虫)
response = urllib.request.urlopen("http://www.baidu.com")
print(response)
#<http.client.HTTPResponse object at 0x0000029F41E34E20>
print(response.read())#读取对象信息=网页源代码(乱码)
print(response.read().decode('utf-8'))#decode-用中文格式解析解码(更正常)
#get请求直接打开网页,可能会被认为是爬虫因此不成功。可以获取网页响应信息
  1. 获取一个post请求操作
#获取一个post请求(需要服务器相应)
#用于模拟用户真实登录(不被认为是爬虫)
#response = urllib.request.urlopen("http://httpbin.org/post") 出错
#print(response.read())#urllib.error.HTTPError: HTTP Error 405: METHOD NOT ALLOWED
#纠正-增加data
import urllib.parse
#表单-储存键值对
data = bytes(urllib.parse.urlencode({"hello":"wolrd"}),encoding="utf-8")#将键值对封装成数组转化为2进制
#http://httpbin.org/请求和相应测试网址
response = urllib.request.urlopen("http://httpbin.org/post",data = data)
print(response.read().decode("utf-8"))#utf-8格式
  1. 超时处理
try:
    response = urllib.request.urlopen("http://httpbin.org/get",timeout=1)
    #urllib.error.URLError: <urlopen error timed out>-异常
    print(response.read().decode("utf-8"))
except urllib.error.URLError as e:
    print("time out")
  1. 几种打印响应的方法
response = urllib.request.urlopen("https://www.baidu.com")
# print(response.status)#状态码/错误代码
# print(response.getheaders())#头部信息
print(response.getheader("server"))#单独头部的server信息
  1. 反爬虫程序(将爬虫伪装成正常的浏览器访问页面)
    个人理解:在爬虫时带上页面的User-Agent信息即可,获取办法:打开网页->Fn+F12->刷新网页单击停止,点击第一个横条->页面拉到底部直接复制
url = "http://httpbin.org/post"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63"}
#头部信息-将爬虫操作伪装成浏览器
#访问网址对应的头部信息复制
data = bytes(urllib.parse.urlencode({'name':'eric'}),encoding="utf-8")
#请求对象
req = urllib.request.Request(url=url,data=data,headers=headers,method="POST")
#响应对象
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
  1. 访问豆瓣
url = "https://www.douban.com"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63"}
req = urllib.request.Request(url=url,headers=headers)
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
  1. conclusion
    爬虫核心语句req = urllib.request.Request(url=url,headers=headers) #url=网址,headers=User-Agent键值对
    响应:response = urllib.request.urlopen(req)#也可以直接输入网址
    输出:print(response.read().decode('utf-8'))#增加中文解码减少乱码
  2. 爬取数据
#得到一个指定url的网页内容
def askUrl(url):
    head = {#模拟浏览器头部信息向豆瓣服务器发送笑死,将请求伪装成正常访问,而不是爬虫
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63"
    }   #用户代理表示告诉豆瓣机器版本,浏览器版本信息,本质上是告诉浏览器可以接受什么水平的内容
    request = urllib.request.Request(url,headers=head)#封装信息
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        print(html)
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)       #错误代码
        if hasattr(e,"reason"):
            print(e.reason)     #错误原因

    return html

如果有多个页面需要爬取

def getData(baseurl):
    #for循环获取多个页面的数据(start=i*25)
    for i in range(0,10):           #调用获取信息的函数10次
        url = baseurl + str(i*25)   #强制转换为字符串类型
        html = askUrl(url) 			#保存函数返回值
  • 解析数据

  • 保存数据

python可视化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值