Python crawler and visualization (basic syntax)

Python crawler and visualization

String:

increase:

a.append (the element to be appended by b) Append b as a whole to a

a.extend(b) append each element in the b list to the a list one by one

a.insert(1,3) specifies the subscript position to insert the element, the first represents the subscript, and the second represents the element object

delete:

del movieName[2] delete the element with the specified subscript

movieName.pop() pops the last element at the end

movieName.remove("sdadas") delete the element of the specified content

check:

a.index("a",1,4) Find the element with the specified subscript, return the index value, range interval, left closed and right open, if not found, an error will be reported

a.count("d") count how many times an element appears

Sort and reverse:

a.reverse() Reverse all elements of the list and reverse all elements of the list

a.sort() ascending order

a.sort(reverse()) descending order

Tuple:

Can contain any number or string, can be read by index, read by range, left open and right closed

Modified: tuple elements cannot be modified

Increase: connect two tuples

Delete: del tup1 delete the entire tuple variable, print data shows name tup1 is not defined

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

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

dictionary:

Unordered object set, using key-value pairs (key-value) storage, can be quickly read

In the same dictionary, the key value cannot be repeated

Direct access to the non-existent key will report an error. In this case, use the dictionary name.get("key") If there is no corresponding key, it will return none by default

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

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

increase:

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

delete:

1) of 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}
删除后:{}

change:

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

info["age"] = 20

print(info["age"])

check:

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

Insert picture description here

set:

set collection

Set is similar to dict. It is also a set of keys, but does not store value. Since the key cannot be repeated, there is no duplicate key in the set.

The set is unordered, and repeated elements will be automatically filtered (can be used for deduplication)
Insert picture description here

function:

#函数的定义
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

file:
Insert picture description here

Insert picture description here

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

Open the file, W mode (write mode), the file is automatically created if it does not exist.

The read method reads the specified character, and it is positioned at the head of the file at the beginning, and moves backward by the specified number of characters each time it is executed

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() Read all files as a list at one time, each line represents a string element

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() #read one line at a time

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

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

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

print("2:%s"%context)

New directory:

import os
	os.mkdir("张三")

Get the current directory:

import os
	os.getcwd()

Change the default directory:

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

Get a list of directories:

import os
	os.listdir(./)

Delete the list before the order:

import os
	os.rmdir("张三")

abnormal:

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       
           异   常             
------------------------------
错了哈哈啊哈    

Get error description as res:

try:
 print(num)

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

Execption catch all exceptions


try

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

Nested exception application

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!!
文件关闭

Guess you like

Origin blog.csdn.net/weixin_44192389/article/details/109300103