Python爬虫与可视化(语法基础)

Python爬虫与可视化

字符串:

增:

a.append(b要追加的元素) 将b作为一个整体追加到a中

a.extend(b)将b列表中的每一个元素逐一追加到a列表中

a.insert(1,3)指定下标位置插入元素,第一个表示下标,第二个表示 元素对象

删:

del movieName[2] 删除指定下标的元素

movieName.pop() 弹出末尾最后一个元素

movieName.remove(“sdadas”) 删除指定内容的元素

查:

a.index(“a”,1,4) 查找指定下标的元素,返回索引值,范围区间,左闭右开,找不到则报错

扫描二维码关注公众号,回复: 12048805 查看本文章

a.count(“d”) 统计某个元素出现几次

排序和反转:

a.reverse() 将列表所有元素反转 将列表所有元素反转

a.sort() 升序

a.sort(reverse()) 降序

元组:

可以包含任意数字或字符串,可按索引读取,按范围读取左开右闭

改:元组元素不可修改

增:连接两个元组

删: del tup1 删除整个元组变量,打印数据显示 name tup1 is not defined

tup1 = ("abc","def",2000,2020)

print(tup1[0])
print(tup1[-1])
print(tup1[1:5])

字典:

无序对象集,使用键值对(key-value) 存储,可快速读取

同一字典,键(key)值不可重复

直接访问不存在的键会报错,此时使用 字典名称.get(“key”) 若没有对应的key则默认返回none

print(info.get("status"))					#None

print(info.get("doub","无对应键值对"))		#没有找到,打印:无对应键值对

增:

# info = {"name":"吴彦祖","age":12}
# newID = input("请输入学号:")
# info["id"] = newID
# print(info["id"])

删:

1)del info[“key”]

info = {"name":"吴彦祖","age":12}
print("删除前:%s"%info["name"])
del info["name"]    #删除指定键值对后会报错
print("删除后:%s"%info["name"])

Traceback (most recent call last):
  File "E:/pythonProject/demo6.py", line 56, in <module>
    print("删除后:%s"%info["name"])
KeyError: 'name'
删除前:吴彦祖

2)info.clear()

info = {"name":"吴彦祖","age":12}
print("删除前:%s"%info)
info.clear()    
print("删除后:%s"%info)


删除前:{'name': '吴彦祖', 'age': 12}
删除后:{}

改:

info = {"name": "吴彦祖", "age": 12}

info["age"] = 20

print(info["age"])

查:

info = {"name": "吴彦祖", "age": 12}
print("#得到所有的键(列表)----------------------------")
print(info.keys())

#得到所有的键(列表)----------------------------
dict_keys(['name', 'age'])


print(" #得到所有的值(列表)---------------------------")
print(info.values())

 #得到所有的值(列表)---------------------------
dict_values(['吴彦祖', 12])


print("#得到所有的项(列表),每个键值对是一个元组----------")
print(info.items())

#得到所有的项(列表),每个键值对是一个元组----------
dict_items([('name', '吴彦祖'), ('age', 12)])


print("#遍历所有的键----------------------------------")
for key in info.keys():
    print(key)
    
    
#遍历所有的键----------------------------------
name
age


print("#遍历所有的值----------------------------------")
for value in info.values():
    print(value)
    
    
#遍历所有的值----------------------------------
吴彦祖
12


print("#遍历所有的键值对----------------------------------")
for key,value in info.items():
    print("key=%s,value=%s"%(key,value))

#遍历所有的键值对----------------------------------
key=name,value=吴彦祖
key=age,value=12

myList = ["a","b","c","d"]
print("#将元组转换为枚举类型----------------------------------")
print(enumerate(myList))

<enumerate object at 0x03286E28>


for i,x in enumerate(myList):
    print(i+1,x)
    
0 a
1 b
2 c
3 d

在这里插入图片描述

集合:

set集合

set和dict类似,也是一组key集合,但是不存储value,由于key不能重复,所以在set中,没有重复的key

set是无序的,重复元素会被自动过滤(可以用于去重)
在这里插入图片描述

函数:

#函数的定义
def printfinfo():
    print("------------------------------")
    print("    人生苦短,我用python         ")
    print("------------------------------")

------------------------------
    人生苦短,我用python         
------------------------------


#函数调用
printfinfo()

2


#带参数的函数
def add2Num(a,b):
    c = a + b
    print(c)

33



add2Num(1,1)

#带返回值的函数
def  add2Num(a,b):
    return a + b

res = add2Num(11,22)
print(res)


#返回多个值的函数
def divid(a,b):
    shang = a//b
    yushu = a % b
    return shang,yushu      #对个返回值用,分隔

sh,yu = divid(5,2)  #需要使用多个值来保存返回内容

print("商:%d\n余数:%d"%(sh,yu))

商:2
余数:1

文件:
在这里插入图片描述

在这里插入图片描述

f = open("test.txt","w")

打开文件,W模式(写模式),文件不存在就自动创建。

read方法读取指定的字符 ,开始时定位在文件头部,每执行一次向后移动指定字符数

f = open("test.txt","r")

context = f.read()

print(context)

# context = f.read(10)

print(context)

f.close()


i am here,hello world!!
i am here,hello world!!
i am here,hello world!!
i am here,hello world!!
i am here,hello world!!
i am here,hello world!!
i am here,hello world!!

context = f.readlines() 一次性读取全部文件为列表,每行表示一个字符串元素

f = open("test.txt","r")

context = f.readlines()     #一次性读取全部文件为列表,每行表示一个字符串元素

# print(context)

i = 1

for a in context:
    print("%d    %s"%(i,a))
    i += 1
    
    
    
1    i am here,hello world!!

2    i am here,hello world!!

3    i am here,hello world!!

4    i am here,hello world!!

5    i am here,hello world!!

6    i am here,hello world!!

7    i am here,hello world!!

context = f.readline() #一次读一行

f = open("test.txt","r")

context = f.readline()     #一次性读取全部文件为列表,每行表示一个字符串元素

print("1:%s"%context)
context = f.readline()

print("2:%s"%context)

新建目录:

import os
	os.mkdir("张三")

获取当前目录:

import os
	os.getcwd()

改变默认目录:

import os
	os.chdir("../")

获取目录列表:

import os
	os.listdir(./)

删除单前目录:

import os
	os.rmdir("张三")

异常:

print("--------test1--------------")

f = open("123.txt", "r")        #用只读模式打开一个不存在的文件会报错

print("--------test2--------------")    #程序在上一步中止,这句代码不会被执行

try:
    print("--------test1--------------")

    f = open("123.txt","r")

    print("--------test2--------------")

except IOError:     #   文件没找到,属于IO异常(输入输出异常)
    pass            #   捕获异常后执行的代码



------------------------------
      人生苦短,我用python       
           异   常             
------------------------------
--------test1--------------

try:
 print(num)

except (IOError,NameError):    
    print("错了哈哈啊哈")            #   捕获异常后执行的代码
    
------------------------------
      人生苦短,我用python       
           异   常             
------------------------------
错了哈哈啊哈    

获取错误描述 as res:

try:
 print(num)

except (IOError,NameError) as result:
    print("错了哈哈啊哈")            #   捕获异常后执行的代码
    print(result)
    
    
------------------------------
      人生苦短,我用python       
           异   常             
------------------------------
错了哈哈啊哈
name 'num' is not defined

Execption 捕获所有异常


try

execpt Execption as result:		#execption可以捕获任何异常
	print(result)

嵌套异常应用

import time

try:
    f = open("test1.txt","r")

    try:
        while True:
            context = f.readline()
            if len(context)==0:
                break
            time.sleep(2)
            print(context)
    finally:
        f.close()
        print("文件关闭")

except Exception as result:
    print("发生异常。。。。")
    print(result)
    
    
------------------------------
      人生苦短,我用python       
           异   常             
------------------------------
i am here,hello world!!   1

i am here,hello world!!   2

i am here,hello world!!   3

i am here,hello world!!

i am here,hello world!!

i am here,hello world!!

i am here,hello world!!
文件关闭

猜你喜欢

转载自blog.csdn.net/weixin_44192389/article/details/109300103