python总结

python windows安装

https://www.python.org/downloads/release/python-2713/ --官网

python -v python -V 的区别:python -V (大写) 与 python --version 功能相同, 查看python 版本;python -v (小写) 是以一种特殊模式进入 python, 该模式下每次有模块被初始化就会打印相应信息, 展示载入的模块名或者内置模块。

pycharm

下载地址
pycharm 安装第三方模块

1.点击顶部菜单栏中的 "File"(文件),然后选择 "Settings"(设置)\\
或者使用快捷键 Ctrl+Alt+S
2.在设置窗口中,选择 "Project: 项目名" 下的 "Python Interpreter"(Python解释器)。
3.点击右上角的加号 + 按钮,搜索要安装得模块名字如pygame
import pygame
print(pygame.__version__) ##查看版本

在这里插入图片描述

因为Pycharm 2020.2.2支持的Python最高版本就是Python 3.9。

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

爬虫

模块随机获取UA: fake-useragent
pip install fake-useragent
from fake_useragent import UserAgent
#实例化一个对象
ua=UserAgent()
#随机获取一个ie浏览器ua
print(ua.ie)
#随机获取一个火狐浏览器ua
print(ua.firefox)

#######Linux 安装

1、安装依赖包
首先安装gcc编译器,gcc有些系统版本已经默认安装,通过 gcc --version 查看,没安装的先安装gcc,yum -y install gcc
2、安装其它依赖包,(python3.7.0以下的版本可不装 libffi-devel)
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
3、在https://www.python.org/ftp/python/中选择自己需要的python源码包,我下载的是python3.7.0;找到downloads

wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz
cd /usr/local
tar -zxvf Python-3.7.0.tgz
mkdir /usr/local/python3 
cd Python-3.7.0
./configure --prefix=/usr/local/python3
make && make install
ln -s /usr/local/python3/bin/python3.7 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.7 /usr/bin/pip3
python --V 或 python --version
python3----执行


注释内容: 
单行注释:#
多行注释:''' 内容'''""" 内容"""
  #!/usr/bin/python
  # -*- coding: UTF-8 -*-
  counter = 100  # 赋值整型变量
  miles = 100.0  # 浮点型
  name = "Python"  # 字符串
print ("Name is: %s ,miles is :%s" %(name,miles))
print(param) ##打印变量
print(f"size is: {file_size}bytes") ##打印变量

字符串前缀:r\b\f
r前缀:表示字符串原始字符串,不存在转义 r"C:\usrs\ren"
f前缀:格式化字符串,可以包含表达式和变量,并使用大括号
print(f"size is: {file_size}bytes") ##打印变量

pycharm 使用

Tab / Shift + Tab:缩进、不缩进当前行
Ctrl + /:行注释/取消行注释
Ctrl + Shift + /:块注释

*与**的区别

函数中的*和**,参数前面加上星号 ,意味着参数的个数不止一个,另外带一个星号参数的函数传入的参数存储为一个元组(tuple),带两个星号则是表示字典(dict)。

a,b,*c=[1,2,3,4,5] #a 等于1;b 等于2;c等于[3,4,5]

定义函数时,一个*的情况:
def myprint(*params):
    print(params)

myprint(1,2,3)
###结果(1,2,3)

 def myprint(*params,x) :
     print(params)
     print(x)
myprint(1,2,x=3) ###要这样写,params=(1, 2)

定义函数时,两个**的情况: 类似字典的形式
def myprint2(**params):
print(params)
myprint2(x=1,y=2,z=3)
结果为字典:{‘z’:3,‘x’:1,‘y’:2}

def test(a,b,*args,**kwargs):
    print(a)
    print(b)
    print(args)
    print(kwargs)

test(1,2,3,4,e=5,f=6)
结果为:
1
2
(3, 4)
{‘e’: 5, ‘f’: 6}

单个*传递可变量的参数

####传递可变量参数#######
[root@hadoop101 python_test]# cat 11.py
#! /usr/bin/python3

def Sum_args(*args): ##将1,2,3,4,5,6作为元组列表传递
    total = 0
    for i in args
        total += i
    return total

result = Sum_args(1,2,3,4,5,6)
print("the result is:",result)

[root@hadoop101 python_test]# python3 11.py
the result is: 21


######拼接变量#####
>>> num=[1,2,3,4,5,6]
>>> result = [*num,6,7,8]
>>> print(result)
[1, 2, 3, 4, 5, 6, 6, 7, 8]

**传递可变量的参数,解析字典

#######传递可变量的关键字参数###################
[root@hadoop101 python_test]# cat 11.py
#! /usr/bin/python3

def print_dict(**kwargs):
    for key,value in kwargs.items():
        print(key,value)

print_dict(name="rcs",age=31,city="shandong")

[root@hadoop101 python_test]# 
[root@hadoop101 python_test]# python3 11.py
name rcs
age 31
city shandong

######拼接字典######
>>> defaults = {"color": "red","size": "B"}
>>> add_para = {"item": "1","course":"Math"}
>>> print(add_para)
{'item': '1', 'course': 'Math'}
>>> print(defaults)
{'color': 'red', 'size': 'B'}
>>> result = {**defaults,**add_para}
>>> print(result)
{'color': 'red', 'size': 'B', 'item': '1', 'course': 'Math'}
>>> 

常用函数

列表、字典、元组、集合、字符串

列表

list = [1,'hello',10]   ##创建列表2
list2 = list(['hong','li']) ##创建列表1
list.index('hello') ##列表查询
list[0]
list[-2] ##获取列表中的单个元素
list1[:2] ##切片 list[start:stop:step]
判断元素是否在列表中: 
元素 in 列表名 ;;;元素 not in 列表名
元素遍历:
for 迭代元素 in 列表名:

lst.sort()  ##默认从小到大升序排序
lst.sort(reverse=True) ##降序排列

字典

字典创建:
Dic={'A':99,'B':90}  #方法1
Dic=dict(name='A',age=10) #方法2
字典获取:
Dic['A'] ##方法1
Dic.get('A')
Dic.keys() #获取所有keyy
Dic.values() #获取所有value
Dic.items()  #获取所有key、values对

字典生成式:
key=['A','B']
value=[99,100]
{key:value for key,value in zip(key,value)}

dict.get(key, default=None)
key – 字典中要查找的键。
default – 如果指定键的值不存在时,返回该默认值None;也可指定想要返回的值。

Dic={'A':99,'B':90,'C':'dddddddd'}
print(Dic.get('C')) ##输出key为C的value
DD=Dic.get('D')
####判断key为D的是否存在,如果不存在就是None
if DD is None: 
    print('not exist111')
########key为E不存在就返回1111,如存在就输出E的value
#####不存在,返回指定的value
EE=Dic.get('E','11111') ##指定如果不存在就返回11111
print(EE)

FF=Dic.get('A')
#######判断key为A是否存在,not None代表存在
if FF is not None:
    print('exist AAA')
###########结果
dddddddd
not exist111
11111
exist AAA

通过in 判断key是否存在

Dic={'A':99,'B':90,'C':'dddddddd'}
if 'A' in Dic:
    print('key A exist')

if 'D' in Dic:
    print('key D exist')
else:
    print('key D not exist')
 
########结果
key A exist
key D not exist

元组

创建:
t=('A',99,'B') ##方法1,使用小括号和逗号
t=tuple(('A',99,'C')) ##方法2,使用内置函数tuple

元组遍历:
for item in 元组名:
	print (item)

集合

集合格式: {A,B,C}

创建
s={'A',9,'C'} ##方法1,使用大括号和逗号
s=set(range(6)) ##使用内置函数set()

集合关系:
是否相等 !===
是否子集: issubset()
是否超集: issuperset()   s.issuperset(s1)
是否无交集: isdisjoint()

字符串

1、字符串拼接: join()
s1=['A','B']
s=''.join(s1)   ####A B
2、字符串查找
S1='aBBBBBBCC'
s='C'
S1.index(s)
index/rindex/find/rfind
split()/rspilt()

字符串比较:

1.使用比较运算符(==!=<<=>>=)来比较字符串---python2/3
str1 = "Hello"
str2 = "World"
if str1 == str2:
    print("字符串相等")
else:
    print("字符串不相等")

2.使用内置函数cmp()来比较字符串--python2
返回一个整数表示字符串比较的结果。如果字符串相等,返回0
str1 = "Hello"
str2 = "World"
result = cmp(str1, str2)
if result == 0:
    print("字符串相等")
elif result < 0:
    print("str1小于str2")
else:
    print("str1大于str2")

3.

列表推导式

##生成1到9的平方列表
squares = [x**2 for x in range(1,10)] 
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
### 筛选出列表的偶数
even_numbers = [x for x in range(1,11) if x % 2 == 0]
print(even_numbers)
[2, 4, 6, 8, 10]

Lambda函数

匿名函数,可以接受任意数量的参数,并且返回一个结果
lambda arguments : expression
arguments是函数接受的参数列表,每个参数之间用逗号隔开。expression 是函数体,是函数的返回值

###定义一个lambda函数,求两个数之和
add = lambda x,y : x+y
result = add(3,4)
print(result)
7

map(function, iterable,)提供的函数对指定序列做映射
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表
>>> def square(x) :            # 计算平方数
...     return x ** 2
...
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数;列表元素挨个传递给x
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

列表处理

1、for 循环遍历
2、while循环遍历
3、enumerate()遍历
4、列表推导式: [expression for item in list] ##[print(i) for i in list1]
5、for循环和range()
6、map()和lambda遍历 lambda arguments: expression
7、zip()遍历列表 :两个或以上列表

for 循环

for 循环遍历元组、列表、字符串、序列:

for 变量 in 序列:
	循环体

test_str = ('python_t','java_t',555,'English')
print("initial list:",test_str)
for element in test_str:
    print(element)
##############
python_t
java_t
555
English

多层for循环:

for 变量1 in 序列1for 变量2 in 序列2:
		循环体

test_str = ['python_t','java_t']
test_num = ['A','B']
for element1 in test_str:
    for element2 in test_num:
        print(element1,element2)
########
python_t A
python_t B
java_t A
java_t B

优化多层for循环,利用zip函数
test_str = ['python_t','java_t']
test_num = ['A','B']
for element1,element2 in zip(test_str,test_num):
    print(element1,element2)
########
python_t A
java_t B

enumerate函数

可以枚举一个序列(如列表、元组、字符串等)—如果用元素和索引
enumerate 函数和for 循环一样,只是该函数可以枚举序列的元素和索引;for 循环只能遍历序列的元素。
enumerate(序列,start=0); #start是枚举的起始索引,默认是0

test_str = ('python_t','java_t',555,'English') ##元组
test_list = ['python_t','java_t',555,'English'] ##或者用列表
print("initial list:",test_str)
for id,value in enumerate(test_str):
    print("index :",id,"value: ",value)  ##输出每个元素的索引和值

#############################
initial list: ('python_t', 'java_t', 555, 'English')
index : 0 value:  python_t
index : 1 value:  java_t
index : 2 value:  555
index : 3 value:  English

for 循环遍历元组、列表、字符串、序列:----如果只是遍历元素值,就用for
for element in seq:

test_str = ('python_t','java_t',555,'English')
print("initial list:",test_str)
for element in test_str:
    print("value: ",element)

############
initial list: ('python_t', 'java_t', 555, 'English')
value:  python_t
value:  java_t
value:  555
value:  English

if函数

if x is None,x为要进行判断的对象,空字符串、空元组、空列表等的都为None。如果判断的对象为None的话那么将会返回False,反之则是True

list = []
if list is None
False

#####输出结果是result is false
current_word = None
if current_word:
    print("11111")
else:
    print("result is false")

###输出结果是111111
if not current_word:
    print("11111")
else:
    print("result is false")
cars = ['audi', 'bmw', 'toyota', 'mazda']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
age = 21
if age >= 18:
    print("You are able to drink!")
age = 1
if age >= 18:
    print("You are able to drink!")
else:
    print("You are too young!")
age = 3
if age <= 4:
    price = 0
elif age < 18:
    price = 4
else:
    price = 10
 
print("Your price is " + str(price) + "$.")
age = 34
if age <= 4:
    price = 0
elif age < 18:
    price = 4
elif age < 65:
    price = 8
else:
    price = 0
age = 70
 
if age <= 4:
    price = 0
elif age < 18:
    price = 4
elif age < 65:
    price = 8
elif age >= 65:
    price = 0
 
print("Your price is " + str(price) + "$.")

字符串处理

split:从前往后分割,可以指定分割多少次,默认分隔符是空格,str.split()
rsplit:从后往前分割,可以指定分割多少次。

>>> AAA="P_CCC-BBB_start_0"
>>> AAA.rsplit('_',2)
['P_CCC-BBB', 'start', '0']
>>> AAA.rsplit('_',2)[0]   ##从后往前分割,分割两次,取第一个
'P_CCC-BBB'

rstrip() 删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符
str.rstrip([chars]) ##chars – 指定删除的字符(默认为空白符)

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
str.strip([chars])

dict 字典

my_dict = {‘name’: ‘Tom’, ‘age’: 18, ‘gender’: ‘Male’}
print(my_dict[‘name’]) # 输出 ‘Tom’ ,获取值的一种方式

dict.get(key, default=None) ###另一种方式获取键值
key是要查找的键名,default是在字典中找不到对应键名时返回的默认值。如果不指定default,默认值为None
print(my_dict.get(‘name’)) # 输出 ‘Tom’
print(my_dict.get(‘height’)) # 输出 None
print(my_dict.get(‘height’, 170)) # 输出 170

my_dict = {‘name’: ‘Tom’, ‘age’: 18, ‘gender’: ‘Male’}
for key, value in my_dict.items():
print(key, value)

########获取所有键值或者值
my_dict = {‘name’: ‘Tom’, ‘age’: 18, ‘gender’: ‘Male’}
for key in my_dict.keys():
print(key)
for value in my_dict.values():
print(value)

判断键值在不:
定义一个字典
person = {‘name’: ‘Tom’, ‘age’: 25, ‘gender’: ‘male’}
检查字典中是否存在指定键
if ‘name’ in person:
print(‘键存在’)
else:
print(‘键不存在’)

Switch Case 函数

Swithc 语句常用于处理多分支函数:Python 3.10版本 更新了switch case结构,直接使用match case 语句:

match <表达式>:
    case <1>:
        <语句块1>
    case <2> | <3> | <4> :
        <语句块2>
    case _:
        <语句块3>

如果所有case都匹配不上的就执行case _:对应的语句块,语句结束。
case后必须跟“字面值”,也就是说,不能是表达式。

#! /usr/bin/python3

import platform
System_Plat = platform.system()
print(System_Plat,type(System_Plat))
match System_Plat:
    case 'Windows':
        PING_ARGS = ['ping', '-n', '1', '-w', '1']
    case _:
        PING_ARGS = ['ping', '-c', '1', '-w', '1']

print(PING_ARGS)

match可以用于列表匹配:
可以进行“模式匹配”
空序列( []),任意长度的序列([ *_ ]);
单个占位符(_)或者捕捉变量(a);
多个占位符(*_)或者捕捉变量 (*a);
alist = [int(x) for x in input().split()]
print("输入了:", alist)
match alist:
    case [ ]:
        print("空列表")
    case [1, _, third]:
        print("这是1开头的三个数,第三个数是:", third)
    case [1, *_, last]:
        print("这是1开头的列表,最后一个数是:", last)
    case [*_, 2]:
        print("这是以2结尾的列表!")
    case [_, 0, *remains]:
        print("这是第二个数为0的列表,0后面是:", remains)
    case [*_]:
        print("都没匹配上的随便列表。")

.format 格式化

$ cat format.py
print("my name is {}, this year is {}.".format("xiaomi",18))
#通过数字索引传入参数
print("my name is {0},lived in {1}".format("cs","shandong"))
#关键字可以随便放置
print("my year is {age} , i am {college}".format(college="shanxi",age="18"))

##输出结果:
$ python format.py
my name is xiaomi, this year is 18.
my name is cs,lived in shandong
my year is 18 , i am shanxi

join 函数

‘sep’.join(seq)
ep: 代表分隔符, 可以是单个字符如: , . - ; 等,也可以是字符串如: ‘abc’。
seq: 代表要连接的元素序列,可以是字符串、元组、列表、字典等。

注:'sep’和seq都只能是string型,不能是int型和float型。

assert()函数

断言函数:用于判断是否会发生异常吗,测试表达式。
返回值为真,程序继续往下执行;返回值为假,就会触发异常。
assert expression [, arguments]
expression:表示要检测的表达式
arguments:给出报错提示

$ cat assert.py
assert 1==2, 'no equal'
assert 1==1, 'equal'
print('continue')

##输出结果output:
$ python assert.py
Traceback (most recent call last):
  File "assert.py", line 1, in <module>
    assert 1==2, 'no equal'
AssertionError: no equal

$ cat assert.py
assert 1!=2, 'no equal'
assert 1==1, 'equal'
print('continue')

##输出结果output:
$ python assert.py
continue

等价于:

if not 1 != 1: # 判断表达式是否征程
    raise AssertionError('ddddd')  # 抛出异常的信息

##输出结果:
Traceback (most recent call last):
  File "assert.py", line 6, in <module>
    raise AssertionError('ddddd')
AssertionError: ddddd

with open 函数

打开文件,使用后,会自动关闭文件,相对open()省去了写close()的麻烦

###删除文件空行

# 打开原始文本文件
with open('input.txt', 'r') as file:
    lines = file.readlines()
    
# 去除每行前后的空格并判断是否为空行
new_lines = [line for line in lines if line.strip() != ""]
 
# 将处理过的内容写入新的文本文件
with open('output.txt', 'w') as file:
    file.writelines(new_lines)

将结果写入临时文件并去除换行符

# 将结果写入临时文件
with open(file_path, 'a', encoding="utf-8") as file:
    print(r.text, file=file, end='')

# 定义文件路径
file_path = "example.txt"
# 打开文件并清空内容
with open(file_path, mode="w") as file:
    pass
 
with open(file="./文件",mode="r/w/a",encoding="utf-8") as f:
    data=f.read/write()
    print(data)
     file.write(data+ "\n")  ##写入文件并换行

r:	以只读方式打开文件。文件的指针将会放在文件的开头。这是**默认模式**。文件不存在报错
r+: 打开一个文件用于读+写。文件指针将会放在文件的开头。文件不存在报错
with open(file="./log31.py",mode="r",encoding="utf-8") as f:
    data=f.read()
    print(data)
Traceback (most recent call last):  ##文件不存在就报错
  File "with_open.py", line 1, in <module>
    with open(file="./log31.py",mode="r",encoding="utf-8") as f:
FileNotFoundError: [Errno 2] No such file or directory: './log31.py'

w:	打开一个文件只用于写入。如果**该文件已存在则将其覆盖**。如果该文件不存在,创建新文件。文件指针将会放在文件的结尾。
w+:	打开一个文件用于读+写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。文件指针将会放在文件的结尾。
$ cat with_open.py  ##存在就覆盖,不存在就创建;写之前都是清空
with open(file="./log31.py",mode="w+",encoding="utf-8") as f:
    data_write=f.write('dddddddddd')
    f.seek(0)   ##移动光标到行首,再读内容就行了
    data=f.read()
    print(data)

a:	打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果**该文件不存在,创建新文件进行写入**。

a+:	打开一个文件用于读+写。如果该文件已存在,文件指针将会放在文件的结尾,要加.seek(0)才能读。文件打开时会是追加模式。如果**该文件不存在,创建新文件**用于读写。
$ cat with_open.py  ##文件不存在就创建,追加的方式
with open(file="./log311.py",mode="a+",encoding="utf-8") as f:
    data_write=f.write('ddddddddddi111\n')

在这里插入图片描述

  1. f.read()

f.read(size)在text mode下会读取一定数量的数据并且以string的方式返回。
f.read() 把所有的字一次性读出并作为一个大的字符串。for遍历时为单字

f.read()
‘This is the entire file.\n’

$ cat read.py
with  open('word.txt', 'r', encoding='utf8') as f:
    seq = f.read()
    for line in seq:
        print(line,type(line),len(line))

##输出结果output:
$ python read.py
1 <class 'str'> 1
. <class 'str'> 1
  <class 'str'> 1
f <class 'str'> 1
i <class 'str'> 1
r <class 'str'> 1
s <class 'str'> 1
……
……
  1. f.readline()
    f.readline()每次从file中读取一行,以一个string的形式返回并且在string的末尾加上一个换行符 \n,只有当文件不再在一个新行处结束时这个末尾换行符\n才会被省略。在f.readline()函数返回一个空string时,意味着已经读到了file的末尾。
    f.readline() 只读取第一行,并作为一个字符串输出。for遍历时为单字。
$ cat read.py
with  open('word.txt', 'r', encoding='utf8') as f:
    seq = f.readline()
    for line in seq:
        print(line,type(line),len(line))

##结果:
$ python read.py
1 <class 'str'> 1
. <class 'str'> 1
  <class 'str'> 1
f <class 'str'> 1
i <class 'str'> 1
r <class 'str'> 1
s <class 'str'> 1
t <class 'str'> 1
  <class 'str'> 1
l <class 'str'> 1
i <class 'str'> 1
n <class 'str'> 1
e <class 'str'> 1

 <class 'str'> 1

  1. f.readlines()
    使用f.readlines()函数或者list(f)去读取all the lines of a file 到一个列表中去in a list。
    f.readlines() 将整个文本全部读出并输出一个列表,把每行的字做为一个字符串。for遍历时为一行。
$ cat word.txt
1. first line
2. second line
3. third line
4. four line

$ cat read.py
with  open('word.txt', 'r', encoding='utf8') as f:
    seq = f.readlines()
    for line in seq:
        print(line,type(line),len(line))

##输出结果output:
$ python read.py
1. first line
 <class 'str'> 14
2. second line
 <class 'str'> 15
3. third line
 <class 'str'> 14
4. four line
 <class 'str'> 13


常用模块

Matplotlib模块

Matplotlib 是Python中类似Matlab绘图工具
C:\Users\Administrator>pip install matplotlib ##默认会安装以下模块
Installing collected packages: six, pyparsing, pillow, packaging, numpy, kiwisolver, fonttools, cycler, python-dateutil, contourpy, matplotlib
Successfully installed contourpy-1.1.1 cycler-0.12.0 fonttools-4.43.0 kiwisolver-1.4.5 matplotlib-3.8.0 numpy-1.26.0 packaging-23.1 pillow-10.0.1 pyparsing-3.1.1 python-dateutil-2.8.2 six-1.16.0

查看版本:
C:\Users\Administrator>python -c “import matplotlib; print(matplotlib.version)”
3.8.0

import matplotlib.pyplot as plt
fig = plt.figure()   ##先打开一个画板
ax = fig.add_subplot(111)  ##选择图的位置
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis') ##横坐标是从0.5-4.5;纵坐标是从-2-8
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(221) ##在将画板分成2*2的格式,在第一个画板画图
ax2 = fig.add_subplot(222) ##在将画板分成2*2的格式,在第二个画板画图
ax3 = fig.add_subplot(224) ##在将画板分成2*2的格式,在第四个画板画图
ax1.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis')
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
fig = plt.figure()
fig, axes = plt.subplots(nrows=3, ncols=3)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')
plt.show()

在这里插入图片描述

numpy 模块

安装完Matploblib模块,会自动安装这个模块;Numpy系统是Python的一种开源的数值计算扩展。这种工具可以用来存储和处理大型矩阵。Numpy提供了两种基本的对象:ndarray(N-dimensional Array Object)和 ufunc(Universal Function Object)。ndarray是存储单一数据类型的多维数组,而ufunc则是能够对数组进行处理的函数。

pip install numpy
import numpy as np	

np.random.rand(20,2)  ##生成20行,2列的二维数据,值在0-1之间
>>> np.random.rand(20,2).shape ##数组的尺寸
(20, 2)
>>> np.random.rand(20,2).size ##数组的元素个数
40

>>> np.array([[1,2,3],[4,5,6]])  ##np.array()的作用就是把列表转化为数组,生成数组,数组是有维度的,这就是生成2*3的一个数组
array([[1, 2, 3],
       [4, 5, 6]])
>>> type(np.array([[1,2,3],[4,5,6]]))
<class 'numpy.ndarray'>
>>> 
>>> np.array([[1,2,3],[4,5,6]]).dtype  ##数组array的默认类型
dtype('int64')
array = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.float32) 

np.array([1, 2, 3]) #一维数组
np.array([(1, 2, 3), (4, 5, 6)]) #二维数组

>>> np.zeros((3, 3))
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])


#一维等差
np.arange(5) #array([0, 1, 2, 3, 4]) 
# 二维等差
np.arange(6).reshape(2, 3) 

结果:
array([[0, 1, 2],
       [3, 4, 5]])

np.eye(3)

结果:
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

#一维,等间隔

np.linspace(1, 10, num=6) #array([ 1. ,  2.8,  4.6,  6.4,  8.2, 10. ])
>>> a = np.array([1, 2, 3, 4, 5])
>>> a[0]
1
>>> a[-1]
5
>>> a[0:2]
array([1, 2])
>>> a[:-1]
array([1, 2, 3, 4])
>>> a = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
>>> print(a)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
>>> a[0]
array([1, 2, 3])
>>> a[-1]
array([7, 8, 9])

>>> 

Pandas 模块

Pandas 看作是 Python 版的 Excel
pandas官网 http://pandas.pydata.org/ 可以供查阅API和更多教程
C:\Users\Administrator>pip install pandas

pandas的依赖库有:pip install numpy pytz dateutil setuptools。可以安装Matplotlib

python中使用pandas读取csv文件:

import pandas as pd
df=pd.read_csv('D:\dxpm.csv',encoding="gbk")
print(df)
print(df.head(3)) #查看前三行数据
print(df.tail(3)) #查看后三行数据

python中使用pandas读取excel文件:

import pandas as pd
df = pd.read_excel('data.xlsx')
df = pd.read_excel('data.xlsx', sheet_name=1) #通过指定sheet名或者sheet编号来读取特定的sheet
import pandas as pd
df=pd.DataFrame({'姓名':["小强","小李","小王","张飞"],"年龄":[24,46,22,42],"籍贯":["北京","上海","广州","四川"]})
print(df)
print(df.iloc[:,0])  #提取第1列
df.iloc[:,1:3]  ##提取2-4列

在这里插入图片描述

configparser模块

Pyhton标准库中用来解析配置文件的模块,用来操作配置文件(ini文件)
ini 文件格式,由节、键、值组成
[section]   # 节  
key = value   # key:键,value:值
一个ini格式配置文件中可以有多个 section,但是名字不能重复。每个 section 下可以分多个键值,每个 section 下的键不能相同:MySQL 配置文件格式为 ini 文件,部分内容如下:

[root@hadoop101 ~]# cat /etc/my.cnf | egrep -v "^#|^$"
[mysqld]    ----section
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0
[mysqld_safe]   ----section
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
!includedir /etc/my.cnf.d

安装
[root@hadoop101 ~]# pip install ConfigParser --python2
[root@hadoop101 ~]# pip3 install configparser --python3

操作:

 ini 文件读取操作
config = configparser.ConfigParser()    创建 ConfigParser 对象  
config.read(filenames, encoding=None)   读取配置文件  
config.sections()   获取所有的 section,除 default 节点外
config.default_section  只能获取 default 节点的 section
config.options(section)   获取指定 section 下所有的 key  
config.get(section, option,…)   获取指定 section 下指定 key 的值  
config.items(section,…)   获取指定 section 下所有 key 与 value 
[root@hadoop101 python_test]# cat conf.ini 
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no

#! /usr/bin/python3
import configparser
filenames="/root/python_test/conf.ini"
cf = configparser.ConfigParser()  
cf.read(filenames,encoding='utf-8')  #  先读取ini文件,才能从ini文件中取数据
print(cf.read(filenames,encoding='utf-8'))  ## /root/python_test/conf.ini
print(cf.default_section)   # 只能通过default_section拿到ini文件中的DEFAULT节点
print(cf.sections())  #通过sections可以拿到ini文件中除DEFAULT以外的所有节点
print(cf.defaults()) default节点的数据,是字典格式

##结果:
[root@hadoop101 python_test]# python3 configparser
['/root/python_test/conf.ini']
DEFAULT
['bitbucket.org', 'topsecret.server.com']
OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])


#获取section为topsecret.server.com下所有key
keys = cf.options("topsecret.server.com")
print(keys)
#获取section为topsecret.server.com下所有的key-value
items = cf.items("topsecret.server.com")
print(items)
#获取section为topsecret.server.com,key为forwardx11对应的value
val = cf.get("topsecret.server.com", "forwardx11")
print(val)


AA=cf['topsecret.server.com']['compression']  ##也可以这样读数据
print(AA)

threading 模块

python中使用ping 模块:pip3 install ping3
pip3 install futures
要使用多线程进行 Ping 操作,两种方式,一是安装 concurrent.futures 库。二是用下面的方式
多线程和多进程是并发编程的两种方式:

  • 多线程:一个进程内创建多个线程,每个线程独立执行不同的任务,多个线程共享进程的资源。
  • 多进程:指在操作系统中创建多个独立的进程,每个进程有自己独立的内存空间和资源,可以同时执行不同的任务。
import threading

def task():
    print("hi, I am a thread") #线程要执行的任务

thread = threading.Thread(target=task) #通过threading.Thread类创建线程
thread.start() #启动线程
thread.join()  #等待线程结束,最好代码涉及两个线程的时候,两个线程是同时运行的,但如果让一个先运行,一个后运行,加上这个就行了
print("thread finished")

10 个 Python 线程,你可以使用 Python 的 threading 模块来实现

import threading
 
def worker():
    """线程执行的函数"""
    print("线程启动")
    time.sleep(15)  等待15s
    print("11111")
 
threads = []
for i in range(10):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()
 
for t in threads:
    t.join()

结果:
[root@hadoop101 ~]# ps -elf | grep 111
0 S root       1619   1226  1  80   0 - 216962 futex_ 23:13 pts/0   00:00:00 python3 threading111.py
0 R root       1631   1492  0  80   0 - 28203 -      23:13 pts/1    00:00:00 grep --color=auto 111
[root@hadoop101 ~]# pstree -p 1619
python3(1619)─┬─{python3}(1620)
              ├─{python3}(1621)
              ├─{python3}(1622)
              ├─{python3}(1623)
              ├─{python3}(1624)
              ├─{python3}(1625)
              ├─{python3}(1626)
              ├─{python3}(1627)
              ├─{python3}(1628)
              └─{python3}(1629)
[root@hadoop101 ~]# 

tkinter模块GUI

tkinter库:用于制作可视化的窗口
pyinstaller:直接在cmd中运行,用于打包py
web

pip install tk ##安装
python -m tkinter #检查是否安装
pip install -i pyinstaller https://pypi.tuna.tsinghua.edu.cn/simple/
pip install -i tkinter https://pypi.tuna.tsinghua.edu.cn/simple/

Faker 模块

Faker是一个Python库,用于生成假的数据,用于生成测试用的一些数据。Faker支持多种不同的数据类型,包括但不限于:姓名、地址、邮件、文本、日期、URL等。
pip install faker ##安装,pycharm可以通过alt+ctrl+s 搜索这个faker模块安装

from faker import Faker
fake = Faker('zh_CN')  # 为中国地区生成数据,可以生成中文的数据;也可也不要,生成英文
print(fake.name())  ##随机生成一个名字
print(fake.email()) ##随机生成一个邮箱
print(fake.address()) ##随机生成一个地址  
print(fake.text()) ##随机生成一段文字
print(fake.date())  ##随机生成一个时间1983-03-27
print(fake.date_time()) ##随机生成一个时间1976-03-01 20:51:17
print(fake.url()) ##随机生成一个url
print(fake.phone_number()) ###随机生成一个电话


#########结果
叶玉
panjing@example.net
贵州省东市东城马路f座 673531
li13@example.com
联系信息最后当前都是.出现中心人民孩子这是正在其实.
服务文件产品操作对于.
介绍主题没有客户是否电话也是.免费部分知道文章.中国搜索学习组织软件销售全国.
提高之后进行如此问题音乐.只有品牌而且成功空间.搜索会员的人会员自己来源本站.
需要技术发现虽然只要什么.一种语言出现通过重要.以及看到因为认为研究那个名称.
显示日本问题.
活动那么特别实现.电脑设备资源无法还是应该.
1983-03-27
1976-03-01 20:51:17
https://leideng.cn/
15652195034


print("1.",fake.name_male())
print("2.",fake.name_female())
print("3.",fake.simple_profile())
print("4.",fake.simple_profile('M'))
print("5.",fake.simple_profile('F'))
print("6.",fake.job())
print("7.",fake.ipv4())
print("8.",fake.ipv6())
print("9.",fake.mac_address())
print("10.",fake.md5())

#####结果
1. 廖慧
2. 邸斌
3. {'username': 'ping75', 'name': '蓝伟', 'sex': 'M', 'address': '云南省台北市平山梧州路B座 779389', 'mail': 'jundai@gmail.com', 'birthdate': datetime.date(1921, 4, 25)}
4. {'username': 'twan', 'name': '王丹', 'sex': 'M', 'address': '山西省兰州市吉区荆门路I座 863797', 'mail': 'fangcui@yahoo.com', 'birthdate': datetime.date(1972, 4, 30)}
5. {'username': 'leizeng', 'name': '郭杨', 'sex': 'F', 'address': '安徽省英县大东南宁路R座 444157', 'mail': 'utao@gmail.com', 'birthdate': datetime.date(2002, 4, 23)}
6. 客户关系经理/主管
7. 162.48.101.178
8. 85b:8898:2b9c:4d40:1795:2371:f54d:dcee
9. b4:1d:57:02:e4:0a
10. 4d9f7b02b3cfbc96095c1d0669bc50f9

>>> faker.word()
'孩子'
>>> faker.words(6)
['类别', '直接', '为什', '如此', '说明', '要求']

>>> faker.random_int()  # 随机生成
2477
>>> faker.random_int(0, 100)  # 限定范围
58
>>> faker.random_digit()  # 一个数字

re 模块

正则表达式匹配
https://www.runoob.com/python/python-reg-expressions.html
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。

re.compile() ##生成正则表达式对象
regex=re.compile(pattern,flags=0)
参数说明:
pattern:正则表达式对象。
flags:代表功能标志位,扩展正则表达式的匹配。

re.findall()  ##匹配目标字符串内容
re.findall(pattern,string,flags=0) ##返回值是匹配到的内容列表
pattern:正则表达式对象。
string:目标字符串
flags:代表功能标志位,扩展正则表达式的匹配。

flag功能标志位:
缩写元字符	说明
A	元字符只能匹配 ASCII码。
I	匹配忽略字母大小写。
S	使得.元字符可以匹配换行符。
M	使 ^ $ 可以匹配每一行的开头和结尾位置

#####可以同时使用福多个功能标志位,比如 flags=re.I|re.S
#非贪婪模式匹配,re.S可以匹配换行符
pattern=re.compile('<div><p>.*?</p></div>',re.S)
re_list=pattern.findall(html)
print(re_list)

###正则表达式的 "." 需要转义因此使用 \.
<div class="movie-item-info">
        <p class="name"><a href="/films/1200486" title="我不是药神" data-act="boarditem-click" data-val="{movieId:1200486}">我不是药神</a></p>
        <p class="star">
                主演:徐峥,周一围,王传君
        </p>
<p class="releasetime">上映时间:2018-07-05</p></div>

编写正则表达式:

<div class="movie-item-info">.*?title="(.*?)".*?class="star">(.*?)</p>.*?releasetime">(.*?)</p>
编写正则表达式时将需要提取的信息使用(.*?)代替,而不需要的内容(包括元素标签)使用.*?代替
    1. re.match 尝试从字符串的起始位置匹配一个模式,匹配成功则返回的是一个匹配对象,,只返回匹配到的一个
>>> import re
>>> s = 'python123python666python888'
>>> print(s)
python123python666python888
>>> result = re.match('python', s)  ##从字符串头匹配,匹配不到就返回None
>>> print(result)
<re.Match object; span=(0, 6), match='python'>
>>> print(result.span())  ##span 返回下标
(0, 6)
>>> print(result.group())  ##返回结果
python
  • 2.re.search 扫描整个字符串,匹配成功则返回的是一个匹配对象,只返回匹配到的一个
    result = re.search(‘python’, s)

  • 3.re.findall,在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表

>>> s = '1python123python666python888'
>>>
>>> result = re.findall('python', s)
>>> print(result)
['python', 'python', 'python']
>>>
>>>print(s.index('python'))  # 1 ,返回第一个python首字母的下标
>>>print(s.index('python', 2))  # 10 ,返回第二个python首字母的下标
>>>print(s.index('python', 3))  # 19,返回第三个python首字母的下标
    1. re.compile
      产生一个正则对象,我们此后匹配规则都可以使用这个对象匹配即可
import re
# 该规则可以匹配出两个同时出现的数字
prog = re.compile('\d{2}')
print(prog.findall('123ab456')) # ['12', '45']

通配符:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
s = ‘1587022xzq’
result = re.match(‘[0-9a-zA-z]{10}’, s) ##只能由字母和数字组成,长度为10位
result = re.match(‘[1-9][0-9]{4,10}KaTeX parse error: Expected 'EOF', got '#' at position 7: ', s) #̲#长度为5-11位,纯数字组成…’, s) ##\d等价于[0-9]
result = re.findall(r’\w+.py\b’, s) ##.检索文件名 格式为 xxx.py,"."被转义为普通字符
去匹配一个反斜杠(即“\”),两种写法
1)普通字符串:‘\’
2)原始字符串:r’’
string = ‘3\8’ ##提取反斜杠前的数字
n = re.search(r’(\d+)\', string)
if n is not None:
print n.group(1) # 结果为:3

r’\‘的过程:
由于原始字符串中所有字符直接按照字面意思来使用,不转义特殊字符,故不做“字符串转义”,直接进入第二步“正则转义”,在正则转义中“\”被转义为了“\”,表示该正则式需要匹配一个反斜杠。
也就是说原始字符串(即r’…')与“正则转义”毫无关系,原始字符串仅在“字符串转义”中起作用,使字符串免去一次转义。
在这里插入图片描述

pattern = r'^A\w+'   ###匹配以字母 A 开头的字符串的正则表达式
result = re.findall(pattern, text)  ##re.findall() 函数返回所有匹配的字符串
print(result)
####\w+ 表示匹配一个或多个字母、数字或下划线,e$ 表示匹配以字母 e 结尾的字符串
pattern = r'\w+e$'  ###匹配以字母 e 结尾的字符串的正则表达式
result = re.findall(pattern, text)
print(result)

time 模块

Python time time()返回当前时间的时间戳。

import time
print(time.time())  ##<class 'float'>
$ python time.py
1693059846.0497906  ##结果是浮点型

time.localtime函数是time库中最常用的函数之一,可以将一个时间戳转换为本地时间

$ cat time.py
import time
t=time.time()
t1=time.localtime(time.time()) ##当不提供任何参数调用localtime函数时,会返回当前的本地时间,即time.localtime()
print(t1)
print(t1.tm_year) 

##结果output:
$ python time.py
time.struct_time(tm_year=2023, tm_mon=8, tm_mday=26, tm_hour=22, tm_min=36, tm_sec=37, tm_wday=5, tm_yday=238, tm_isdst=0)
2023 ##t1.tm_year

time.strftime()可以用来获得当前时间,可以将时间格式化为字符串等等

current_time = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
print(current_time)
print(type(current_time))

##输出结果:
20230826_224814  #current_time
<class 'str'>

Logging模块

logging是python的日志管理模块,用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等。
logging库提供了多个组件:Logger、Handler、Filter、Formatter。
Logger 对象提供应用程序可直接使用的接口,
Handler 发送日志到适当的目的地,
Filter 提供了过滤日志信息的方法,
Formatter 指定日志显示格式。
log模块学习

$ cat log.py
import logging
logging.debug('1. This is debug message')
logging.info('2. This is info message')
logging.warning('3. This is warning message')
logging.error('4. This is error message')
或者下面内容:
logging.log(50, 'This is critical message')
logging.log(40, 'This is error message')
logging.log(30, 'This is warning message')
logging.log(20, 'This is info message')
logging.log(10, 'This is debug message') 等同于logging.debug
结果输出output:
$ python log.py
WARNING:root:3. This is warning message
ERROR:root:4. This is error message

没有输出info和debug的信息的原因,请看下面。
python的日志级别有六种:CRITICAL(50) > ERROR(40) > WARNING(30) > INFO (20)> DEBUG(10) > NOTSET(0),每一个level与一个整数数值。默认日志级别位WARNING,因此只有level高于等于WARNING,或对应整数值大于等于30的日志信息会被输出

DEBUG: 详细信息,通常仅在诊断问题时才受到关注。整数level=10
INFO: 确认程序按预期工作。整数level=20
WARNING:出现了异常,但是不影响正常工作.整数level=30
ERROR:由于某些原因,程序 不能执行某些功能。整数level=40
CRITICAL:严重的错误,导致程序不能运行。整数level=50

logging.basicConfig(level=logging.NOTSET)       #改变日志输出级别
logging.addLevelName(60,'myLoggingLevel')       #自定义日志的对应的整数
logging.error('this is myLoggingLevel')      ##调用自定义的log level方法1
logging.log(60, 'This is myLoggingLevel message') ##调用自定义的log level方法2


logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #日志输出的内容
                datefmt='%a, %d %b %Y %H:%M:%S',     #日期格式
                filename='myapp.log',  #日志文件位置,若不定义,则默认输出在console上
                filemode='w')                        #文件打开方式
import logging

logging.basicConfig(filename='my.log',format="%(asctime)s-%(filename)s-%(lineno)d- %(levelname)s: %(message)s ") ##会将下面的符合要求的写到my.log文件中
##asctime,可读时间,默认格式‘2003-07-08 16:49:45,896',逗号之后是毫秒
logging.addLevelName(60,'myLoggingLevel')
logging.addLevelName(level=25, levelName="SUCCESS")
logging.addLevelName(level=26, levelName="FINISH")
logging.debug('1. This is debug message')
logging.info('2. This is info message')
logging.warning('3. This is warning message')
logging.error('4. This is error message')
%(asctime)s: 日期和时间,eg: 2022-03-05 15:01:45
%(name)s: logging日志器的名字,eg: log.py
%(levelname)s: 日志级别名,eg: DEBUG, INFO, WARNING, ERROR, CRITICAL
%(message)s: 日志信息,eg: Error message
%(lineno)d 调用日志记录函数的源代码所在的行号
%(funcName)s调用日志记录函数的函数名
datefmt:指定时间格式,同time.strftime();
 datefmt='%Y-%m-%d %H:%M:%S'
$ cat my.log
2023-08-25 14:30:58,975-log.py-9- WARNING: 3. This is warning message
2023-08-25 14:30:58,975-log.py-10- ERROR: 4. This is error message
2023-08-25 14:30:58,975-log.py-12- ERROR: this is myLoggingLevel
2023-08-25 14:30:58,975-log.py-13- myLoggingLevel: This is myLoggingLevel message
2023-08-25 14:47:58,189-log.py-9- WARNING: 3. This is warning message
2023-08-25 14:47:58,189-log.py-10- ERROR: 4. This is error message
2023-08-25 14:47:58,189-log.py-12- ERROR: this is myLoggingLevel
2023-08-25 14:47:58,189-log.py-13- myLoggingLevel: This is myLoggingLevel message

  1. getLogger
    初始化的时候我们传入了模块的名称,这里直接使用 __name__ 来代替了,就是模块的名称,如果直接运行这个脚本的话就是 __main__,如果是 import 的模块的话就是被引入模块的名称,这个变量在不同的模块中的名字是不同的,所以一般使用 “__name__” 来表示就好了.
import logging

logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger('__name__') ##就是记述哪个函数跑的代码,如果写成固定值,那就是所有代码都是标记是他跑的,要写成__name__,不要加引号,加引号就是字符串了
logger.critical('critical')
logger.error('error')
logger.warning('warning')
logger.info('info')
logger.debug('debug')

##输出结果output:
$ python log3.py
2023-08-25 21:00:57,819 - __name__ - CRITICAL - critical
2023-08-25 21:00:57,819 - __name__ - ERROR - error
2023-08-25 21:00:57,819 - __name__ - WARNING - warning
2023-08-25 21:00:57,819 - __name__ - INFO - info
2023-08-25 21:00:57,819 - __name__ - DEBUG - debug

####logger = logging.getLogger(__name__)
$ python log3.py
2023-08-26 19:44:57,540 - __main__ - CRITICAL - critical
2023-08-26 19:44:57,540 - __main__ - ERROR - error
2023-08-26 19:44:57,540 - __main__ - WARNING - warning
2023-08-26 19:44:57,540 - __main__ - INFO - info
2023-08-26 19:44:57,540 - __main__ - DEBUG - debug



$ cat log3.py
# -*- coding:utf-8 -*-
import logging

logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger()
logger.critical('critical')
logger.error('error')
logger.warning('warning')
logger.info('info')
logger.debug('debug')

输出结果output:
$ python log3.py
2023-08-25 21:03:51,318 - root - CRITICAL - critical
2023-08-25 21:03:51,318 - root - ERROR - error
2023-08-25 21:03:51,318 - root - WARNING - warning
2023-08-25 21:03:51,318 - root - INFO - info
2023-08-25 21:03:51,318 - root - DEBUG - debug


  1. handle用法

用两个handle,分别打印到控制台和文件

import logging
import sys
 
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
 
# FileHandler 将日志输出到文件log.log
#FileHandler:logging.FileHandler;日志输出到文件。
file_handler = logging.FileHandler('log.log')
file_handler.setLevel(level=logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
 
# StreamHandler 将日志输出到控制台
#StreamHandler:logging.StreamHandler;日志输出到流,可以是 sys.stderr,sys.stdout 或者文件
stream_hanlder = logging.StreamHandler(sys.stdout)
stream_hanlder.setLevel(level=logging.DEBUG)
logger.addHandler(stream_hanlder)

logger.critical('critical')
logger.error('error')
logger.warning('warning')
logger.info('info')
logger.debug('debug')
  1. logger.error
    当报错得时候可以分析具体原因:
    error() 方法中添加了一个参数,将 exc_info 设置为了 True,这样我们就可以输出执行过程中的信息了,即完整的 Traceback 信息。
try:
    result = 10 / 0
except Exception:
    logger.error('fenxi', exc_info=True)

##输出结果output:
fenxi
Traceback (most recent call last):
  File "log4.py", line 27, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

  1. List item

OS 模块

os.path.abspath(__file__)是一个非常有用的函数,它用于获取当前执行脚本的完整路径。
这个函数特别适用于当你需要知道脚本本身在文件系统中的位置时。
__file__是一个特殊的内置变量,它代表了当前被执行的脚本文件的名称
(包括路径,如果脚本被直接运行)
current_path = os.path.abspath(__file__)  ## 输出当前py脚本的绝对路径
print(current_path)

file_path = os.path.dirname(os.path.abspath(__file__))## 输出当前py脚本所在的目录的绝对路径
print(file_path)

file_name='test_excel.py'
apath = os.path.abspath(file_name)  ## 输出当前py脚本的绝对路径
print(apath)
>>> import os
>>> current_path = os.path.abspath(".")
>>> print (current_path)
    /root/python3-test
>>> yaml_path = os.path.join(current_path, "config.yaml") ##拼接
>>> type(yaml_path)
<class 'str'>
>>> print(yaml_path)
   /root/python3-test/config.yaml

os.makedirs('./day24/day25') ##递归创建目录,当目录存在的时候,再执行会报错;当24和25都不在,或者24在 25不在,执行ok
os.mkdir('aa') ##生成单级目录;当目录存在则报错
os.listdir('./day24') ##列出指定目录下的所有文件和子目录,包括隐藏文件,返回结果列表
os.remove('a.txt') #删除文件,不存在则报错
os.chdir("dirname")  #改变工作目录
os.system("bash command") #运行shell命令,只返回状态码,不会输出结果
os.path.exists('./day24') 判断路径存不存在,存在为True
os.path.dirname('/root/AA/24.txt')返回path的目录/root/AA/
os.path.basename('/root/AA/24.txt')返回path最后的文件名24.txt
os.path.isfile('/root/AA/24.txt')  #path是一个存在的文件,返回True
os.path.isdir('/root/AA/') #path是一个存在的目录,返回True
os.path.getsize('/root/AA/24.txt')查看文件的大小
访问、创建、修改时间
os.path.getmtime()
os.path.getatime()
os.path.getctime()
os.path.join() 路径拼接
path = os.path.join('/Users/rcs', 'Desktop/python', 'day19.py')
print(path) # /Users/rcs/Desktop/python/day19.py

os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])
top – 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。

  • root 所指的是当前正在遍历的这个文件夹的本身的地址
  • dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
  • files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
#! /usr/bin/python3

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print("111",os.path.join(root, name))
    for name in dirs:
        print("222",os.path.join(root, name))

a,正在查询的./目录下的单层目录
import os
result = os.walk("./")
for a,b,c in result:   
    print(a)             #a所有目录
b表示这个目录下的各个子目录列表,子目录没有子目录就显示为空列表
import os
result = os.walk("./")
for a,b,c in result:   
    print(b)

c,表示各个目录下的文件列表
import os
result = os.walk("./")
for a,b,c in result:   
    print(c)                 #c,各个目录文件列表
d. 遍历这个目录下所有文件,包括子目录的文件
import os
result = os.walk("./")
for a,b,c in result:
    # a,正在查看的目录 b,此目录下的文件夹  c,此目录下的文件
    for item in c:
        path = os.path.join(a,item)   #
        print(path)

os.seq 默认加/ 或者/
Windows上,文件的路径分隔符是’\’,在Linux上是’/’。

>>> import os
>>> os.sep.join(['hello', 'world'])  ##linux下会自动加/
'hello/world'
>>> 

>>> import os
>>> os.sep.join(['hello', 'world']) ##windows下会自动加\\
'hello\\world'
>>>
>>>

递归创建文件:

    playbook_path = '.\dddd'
    manual_name = 'bbbbb'
    temp_Playbook = playbook_path + os.sep + 'temp' + os.sep + manual_name
#    temp_Playbook = os.path.join(playbook_path, 'temp', manual_name)
    print("temp_Playbook: ",temp_Playbook)
    if not os.path.exists(temp_Playbook):
        os.makedirs(temp_Playbook)
import os
#返回值是个布尔类型的
temp_file = "G:/软件/文件测试/test.py"
os.path.exists(temp_file )
经常用到的(如果文件夹不存在,则创建该文件夹)
if not os.path.exists(temp_file ):
    os.makedirs(temp_file )



shutil 模块

文件和目录操作。用于复制、移动、重命名、删除文件和目录等操作。
import shutil

# 复制文件
shutil.copy('source_file.txt', 'target_directory/')
# 复制文件,保留元数据(如权限、时间戳等)
shutil.copy2('source_file.txt', 'target_directory/')
# 复制文件内容(不包括元数据)
shutil.copyfile('source_file.txt', 'target_file.txt')
# 复制目录及其内容
shutil.copytree('source_directory/', 'target_directory/')
# 移动文件
shutil.move('source_file.txt', 'target_directory/')
# 移动目录
shutil.move('source_directory/', 'target_directory/')
# 删除目录及其内容(包括子目录和文件)
shutil.rmtree('directory/')
# 重命名文件
shutil.move('old_name.txt', 'new_name.txt')
# 重命名目录
shutil.move('old_directory/', 'new_directory/')

shutil.copytree(src, dst)
将递归地复制源目录 src 及其所有子目录和文件到目标目录 dst
目标目录dst已经存在,copytree() 函数会引发 FileExistsError 异常。如果要覆盖已经存在的目录,可以使用 shutil.rmtree() 函数删除目标目录,然后再执行复制操作。

import shutil
import os
def copy_folder(from_dir_path, to_dir_path):
    if os.path.exists(to_dir_path):
        shutil.rmtree(to_dir_path)
    shutil.copytree(from_dir_path, to_dir_path)

python3.8之后有dirs_exist_ok这个参数
shutil.copytree(code_Path,code_buildPath,dirs_exist_ok=True)
如果将 dir_exist_ok 设为 True,则当目标目录存在时,复制操作会继续执行;如果将 dir_exist_ok 设为 False,则会引发 FileExistsError 异常

subprocess 模块

这个模块主要执行外部命令,执行shell命令;类似os.system(‘pwd’)
这个模块来产生子进程,能够处理输入、输出、错误处理和其他操作
import subprocess
程序运行subprocess.Popen()类,父进程创建子进程后,不会等待子进程执行完成。如果需要等待子进程,需要加入wait()方法阻塞父进程。

$ cat os1.py
import os
import subprocess
child = subprocess.Popen('ping www.baidu.com')
print('End') ##没有等child 执行完就print,
print(child)

poll(): 检查进程是否终止,如果终止返回 returncode,否则返回 None。
wait(timeout): 等待子进程终止。
communicate(input,timeout): 和子进程交互,发送和读取数据。
##########
import subprocess
cmd='ping www.baidu.com'
child = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr= subprocess.PIPE)
方法一输出:
shell_out = child.stdout.read()
shell_error = child.stderr.read()
print(shell_out)
print(shell_error)
方法二输出:.communicate会一直等到进程退出,并将标准输出和标准错误输出返回,这样就可以得到子进程的输出了.不需要等待
output, error = child.communicate()
print('output:',output)
print('error:',error)

args:shell命令,可以是str类型,或者listtuple
bufsize:缓冲区
stdin、stdout、stderr:标准输入输出和标准错误日志
subprocess.PIPE:创建Popen对象时,subprocess.PIPE可以初始化stdin、stdout、stderr参数。

结论:如果使用 subprocess.Popen,就不使用 Popen.wait(),而使用 Popen.communicate() 来等待外部程序执行结束。
subprocess意在替代其他几个老的模块或者函数,比如:os.system os.spawn* os.popen* popen2.* commands.*
subprocess模块定义了一个类: Popen
subprocess.Popen(["cat","test.txt"]) ##执行cat test.txt
subprocess.Popen("cat test.txt", shell=True)等价于subprocess.Popen(["/bin/sh", "-c", "cat test.txt"])
subprocess.PIPE 一个可以被用于Popen的stdin 、stdout 和stderr 3个参数的特输值,表示需要创建一个新的管道。
subprocess.STDOUT 一个可以被用于Popen的stderr参数的输出值,表示子程序的标准错误汇合到标准输出


os.system(command)会返回命令执行的返回码,而将命令执行结果输出到屏幕。
os.popen(command).read()可以获取命令执行结果,但是无法获取命令执行的返回码。

$ cat os1.py
import os
output=os.system('pwd')
print('result:',output) ##result: 0

subprocess.run()函数是Python3.5中新增的一个高级函数,其返回值是一个subprocess.CompletedPorcess类的实例

import subprocess
child = subprocess.run('python --version', shell =True,capture_output=True,encoding='utf-8')
print('result:',child)
print('rc:',child.returncode)
print('output:',child.stdout)

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)

encoding: 如果指定了该参数,则 stdin、stdout 和 stderr 可以接收字符串数据,并以该编码方式编码。否则只接收 bytes 类型的数据。
capture_output: 设置为True,将捕获stdout和stderr,从而获执行命令后取返回的内容。
##
$ python os3.py
result: CompletedProcess(args='python --version', returncode=0, stdout=b'Python 3.7.5\r\n', stderr=b'')
rc: 0
output: b'Python 3.7.5\r\n'


p1=subprocess.Popen('cat /etc/passwd',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)    
p2=subprocess.Popen('grep 0:0',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE) ##p2使用P1的输出结果,作为p1输入

import subprocess
p1=subprocess.Popen('ping www.baidu.com',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
p2=subprocess.Popen(' grep Reply',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE)

output, error = p2.communicate()
print('output:',output)
print('error:',error)

subprocess.run()和subprocess.Popen区别在于 subprocess.run() 执行命令并 等待 完成,而使用 subprocess.Popen 你可以在进程完成时继续做你的事情,然后重复调用 Popen.communicate()自己将数据传递和接收到您的流程。

json与yaml区别

  1. JSON
    内容不支持注释
    json(JavaScript Object Notation)是一种轻量级的数据交换格式,由键值对构成的集合组成,通常以文件扩展名.json命名。
    load和dump处理的主要是 文件
    json.load # 读取json文件,返回python 字典对象
    json.dump # 将python 字典写入json文件,文件为json字符串格式,无返回
    loads和dumps处理的主要是 字符串
    json.dumps() # python字典类型转为json字符串类型,返回json字符串[dict->str]
    json.loads() # 将json字符串转为python 字典类型数[str->dict]
    在这里插入图片描述
{
  "name": "R",
  "age": 30,
  "city": "CHINA",
  "pets": [
    {
      "name": "11",
      "species": "cat"
    },
    {
      "name": "22",
      "species": "dog"
    }
  ]
}
例如:读入test.json,通过json.load(f)得到python dict对象,修改python dict对象属性,然后写入新文件test_new.json中
import json
with open('test.json', 'r') as f:
    data = json.load(f)
    print(data)
    print(type(data))
    data["pets"][1]["name"] = "AAAA"  # 修改python dict对象属性
with open('test_new.json', 'w') as f:
    json.dump(data, f)

  1. YAML
    内容支持注释
    注释:YAML支持注释,以井号(#)开头
# 使用python的load()方法读取yaml文件内容(反序列化), 在 yaml.load 方法中, loader 参数有四种:

# 1. BaseLoader:载入大部分的基础YAML
# 2. SafeLoader:载入YAML的子集,推荐在不可信的输入时使用
# 3. FullLoader:这是默认的载入方式,载入全部YAML
# 4. UnsafeLoader:老版本的载入方式
yaml.load(f, Loader=yaml.FullLoader)

# 使用python的dump()方法将python字典写入yaml文件(序列化)
# 当data数据中有汉字时,加上: encoding='utf-8',allow_unicode=True 
yaml.dump(data, f, encoding='utf-8', allow_unicode=True)

- name: C
  age: 30
  hobbies:
    - reading
    - hiking
- name: S
  age: 31
  hobbies:
    - painting
    - cooking

import yaml

# 读yaml,将yaml转python字典
with open('example.yml', 'r') as f:
    dic = yaml.load(f, Loader=yaml.FullLoader)
    print(dic)

dic['nb3'][1] = 'AAAAA'  # 修改nb3的密码

# 写yaml,将python字典写入yaml文件
with open('example_new.yml', 'w') as f:
    yaml.dump(dic, f, encoding='utf-8', allow_unicode=True)

json.dump()
jsonPython模块中的模块提供了一种称为dump()它将Python对象转换为适当的json对象。它是dumps()方法。

yaml 模块

pip install pyyaml ##python3
pip install yaml ##python2

import yaml
#读取配置文件
f = open("./config.yaml", 'r', encoding='utf-8')
#cont返回文件中的所有内容,包括注释字符等。
cont = f.read()
#config返回python字典
#即:{'gama': 0.001, 'sigma': 8.5}
config = yaml.safe_load(cont)
#想获取字典中的某个参数就调用get方法
param = config.get("gama")
#param返回的就是gama对应的值:0.001

json.dump(obj=json_data, fp=open(json_path, mode='w', encoding='utf-8'), indent=2, sort_keys=False,ensure_ascii=False)

ensure_ascii:此参数也仅采用布尔值。如果未将其设置为true,则将非ASCII字符原样转储到输出文件中。默认情况下,该值为true。
sort_keys:此参数为布尔值。如果将其设置为True,则将按升序设置键,否则它们将显示为Python对象

dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,allow_nan=True, cls=None, indent=None, separators=None,default=None, sort_keys=False, **kw)

obj:就是你要转化成json的对象。
其实这个和json.dumps()就是多了一个**fp的文件参数**,一个是关于文件之间的储存,一个是字符串之间的转换。
ensure_ascii=True:默认输出ASCLL码,如果把这个该成False,就可以输出中文

pathlib 模块

Python 3.4 引入的标准库,用于处理文件路径和目录的类。
pip install pathlib

  1. 打印目录
$ cat 14.py
from pathlib import Path
current_working_directory = Path.cwd() ##打印当前目录路径
print(current_working_directory)

yaml_path = Path(current_working_directory, '11.yaml')
print(yaml_path)
print(type(yaml_path)) ##类型为class,最好转为字符串str

##结果output
$ python 14.py
C:\Python\test\test111
C:\Python\test\test111\11.yaml
<class 'pathlib.WindowsPath'>

 2. 文件大小
打印文件大小,判断是否为空
p = Path(current_working_directory, '11.py')
print(p)
file_size = p.stat().st_size
print(file_size)  
print(f"size is: {file_size}bytes") ##打印文件内容是否为空
print(f"file name: {p.name}")  #file name: 11.py
print(f"file name: {p.stem}")  #file name: 11 不带后缀
print(f"name: {p.suffix}")     #name: .py 后缀名字
print(f"super name: {str(p.parent)}") #super name: C:\Python\test\test111 文件的父目录,也就是文件所在的目录

3.对文件进行判断,返回布尔值
print(f"is this exist?: {str(p.exists())}") #判断文件是否存在
print(f"is this a directory?: {p.is_dir()}") #判断文件是否为文件夹
print(f"is this a file?: {p.is_file()}") #判断文件是否为文件

##结果output
is this exist?: True
is this a directory?: False
is this a file?: True

p.parent(),p.parents()  # parent获取path的上级路径,parents获取path的所有上级路径

4.打印目录下所有符合条件的
# glob这个返回的是一个迭代器,需要配合 for循环拿出里面全部的值
# encoding = utf-8
from pathlib import Path

current_working_directory = Path.cwd()
print(current_working_directory)
for i in current_working_directory.glob('*.py'):
    print(i)
##结果output
C:\Python\test\test111\11.py
C:\Python\test\test111\12.py
C:\Python\test\test111\13.py
C:\Python\test\test111\14.py
C:\Python\test\test111\original.py

# 文件路径以及文件创建
# 当文件夹不存在时,直接使用.mkdir(),若该文件夹存在或者创建多级路径会失败,抛出异常
# path.mkdir(exist_ok=True)创建单个文件夹,如果存在则忽略,多级同上
# path(./logs/11).mkdir(exist_ok=True,parents=True)创建多级路径,存在则忽略;会递归创建文件夹

#Path('./somefile.txt').touch(exist_ok=True) 创建单个文件,如果存在则忽略,不做

atexit 模块

python atexit 模块定义了一个 register 函数,用于在 python 解释器中注册一个退出函数,这个函数在解释器正常终止时自动执行,一般用来做一些资源清理的操作

import atexit
@atexit.register
def f():
    print("Finished")

##当所有函数都执行完了,会自动执行这个函数,不用调用

argpase模块

ls -alh /etc/hosts
   ls #为命令
   -alh #为短选项参数
   /etc/hosts # 位置参数
import argparse
parser = argparse.ArgumentParser() #获得一个参数解析器
agrs = parser.parse_args()   #分析参数
parser.print_help() #打印帮助

output结果: 默认打印下面信息
usage: original.py [-h]  打印函数没有参数

optional arguments:  可选参数
  -h, --help  show this help message and exit
argparse不仅仅做了参数定义和解析,还自动帮助生成了帮助信息,尤其是usage可以看到现在的参数是否是自己想要的

参数名称 说明
prog : 程序名字,缺省使用sys.argv[0]的basename
add_help : 自动生成解析器增加-h和- - help选项,默认为True;add_help=True可加可不加,True必须大写
description: 为程序工程添加描述

$ cat 11.py
import argparse

parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list dir or cer') #获得一个参数解析器
agrs = parser.parse_args()   #分析参数
parser.print_help() #打印帮助

##结果output
$ python 11.py
usage: ls [-h]   ##如果加了prog就会打印prog的信息,否则默认打印脚本信息

list dir or cer  ##上面的description信息

optional arguments:  ##如果add_help=False,这行以及下面的信息不会被打印
  -h, --help  show this help message and exit

parser.add_argument(‘path’)
args = parser.parse_args((‘./’,)) #将agrs看作参数列表可迭代对象;这两个是一起用的。意思是将./作为path 参数传
parse_agrs(args=None,namespace=None)
args 是一个参数列表,一个可迭代对象.内部会把可迭代对象转化为list.如果为none则使用命令行传入参数,非None使用args参数的可迭代对象.

$ cat 12.py
import argparse

parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list dir or cer ')
parser.add_argument('path')
args = parser.parse_args(('./',)) #将agrs看作参数列表可迭代对象
print (1,args,args.path)  ##因为add_argument写了path就可以调用这个,如果不是就要看Namespace里面等号前是啥
parser.print_help()

##args的结果是Namespace(path='./');args.path的结果是./(args的参数)
##结果output
$ python 12.py
1 Namespace(path='./') ./  ##print打印的内容;namespace 存储着args的path属性,那么即可通过args.path进行访问
usage: ls [-h] path

list dir or cer

positional arguments:
  path

optional arguments:
  -h, --help  show this help message and exit

非必须位位置参数
定义非必须要位置参数,path,nargs表示可有可无,default默认为.也就是当前目录,help表示帮助目录中显示,

$ cat 12.py
import argparse
parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list dir or cer')
parser.add_argument('path',nargs='?',default='.',help='path help') #位置参数,可有可无,缺省值,帮助
args = parser.parse_args(('/etc',))
print (1,args,args.path)
parser.print_help()

##结果output
$ python 12.py
1 Namespace(path='/etc') /etc
usage: ls [-h] [path]
list dir or cer
positional arguments:
  path        path help
optional arguments:
  -h, --help  show this help message and exit
nargs 表示这个参数接收结果参数
​ ?表示 一个或者没有,可有可无
​ +表示至少一个
​ *表示可以任意个
​ 如果是数字则表示数字代表个数
default 表示如果不提供参数则就是这个值,一般和? *进行配合,因为他都是可以不提供位置参数

$ cat 22.py
import argparse
parser = argparse.ArgumentParser(description='HWM configure script.')
parser.add_argument('-f', '--json_file', default='host_info.json', help="config file path. (Default: 'host_info.json')")
parser.add_argument('-i', '--interface', default='interface.txt', help="hostname.txt file path. (Default: 'interface.txt')")
parser.add_argument('-t', '--timeout', help='Zabbix request timeout.')

args = parser.parse_args()
jsonfile = args.json_file
print (1,args) ##args存了namespace
print(2,jsonfile) 
print(3,args.interface) ##namespace有interface这个参数
##测试结果:
$ python 22.py
1 Namespace(interface='interface.txt', json_file='host_info.json', timeout=None)
2 host_info.json  
3 interface.txt

pip

pip install -U pip  升级pip
pip install package_name 安装软件
pip install selenium==3.3.3 <= 指定最高版本号
pip install -r requirements.txt 批量安装多个软件,将软件名称写到这个文件里面
pip uninstall package_name  卸载软件
pip install -U packagement 升级软件包
pip show -f package_name  列出包信息
pip list -o 查看哪些库需要升级
pip check package_name  验证已安装的库的兼容性依赖
pip download package_name -d "path" #将库下载到本地的指定位置以whl 保存
pip download PyYaml -d "/tmp/"
pip install C:\Users\xxx\Downloads\python_dateutil-2.5.3-py2.py3-none-any.whl

想把一个环境的的pip安装的软件在另一个环境安装,可以用:
pip freeze > requirement.txt

platform

 import platform
 PLANT = platform.system()  #打印系统平台
 print(PLANT)
 ###Linux

Excel

xlrd/xlwt与openpyxl处理Excel的主要区别在于写入操作,其中xlwt针对Ecxec2007之前的版本,即.xls文件,其要求单个sheet不超过65535行,而openpyxl则主要针对Excel2007之后的版本(.xlsx),它对文件大小没有限制。
xlrd:读取xls、xlsx文件,效率非常高。不支持修改!(高版本不支持xlsx,pip install xlrd==1.2.0)
xlwt:写入新xls、xlsx文件,效率非常高。但不支持修改已有表格。数据从(0,0)开始,代表第一行第一列。

  • 1 xlrd
import xlrd
###打印该py脚本所在目录路径
Dir_path = os.path.dirname(os.path.abspath(__file__))
print(Dir_path)
###拼接excel文件和目录
excel_path = os.path.join(Dir_path, 'test_11.xlsx')
print(excel_path)
##打开excel对象
book = xlrd.open_workbook(excel_path)
# sheet1 = book.sheets()[0] ##方法一,打开指定sheet表
# sheet1 = book.sheet_by_index(0)##方法二,打开指定sheet表
sheet1 = book.sheet_by_name('chengji')##方法三,打开指定sheet表

nrows = sheet1.nrows
print('表格总行数', nrows)
ncols = sheet1.ncols
print('表格总列数', ncols)
row2_values = sheet1.row_values(1)
print('第2行值', row2_values)
col3_values = sheet1.col_values(2)
print('第3列值', col3_values)
cell_3_3 = sheet1.cell(1, 2).value
print('第2行第3列的单元格的值:', cell_3_3)
print('sheet nums:', book.nsheets) ##打印该excel

for i in range(0, book.nsheets):
    ws = book.sheet_by_index(i)
    cell_3_3 = ws.cell(1, 2).value
    print('第2行第3列的单元格的值:', cell_3_3)
  • 2 xlwt
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet("sheetName")
ws.write(0, 0, '11111')
ws.write(0, 1, '222222')
ws.write(0, 2, '333333')
row = 1
col = 0
# 从第二行,第一列开始写
# for i in range(0, 10):
#     ws.write(row, col, 123)
#     row += 1
#     col += 1
excel_path1 = os.path.join(Dir_path,'test2.xls')  ##支持xls格式,如果是xlsx会打不开
print(excel_path1)
wb.save(excel_path1)
  • 3 openpyxl
    openpyxl:可读可写可修改,数据从(1,1)开始,代表第一行第一列。
    整理

docx word处理

pip install python-docx

# 添加章节标题
doc.add_heading('第一章:Python 基础', level=1)
# 添加段落
doc.add_paragraph('Python 是一门高级编程语言,易学易用。')
# 保存文档
doc.save('Sample.docx') ##生成一个名为 Sample.docx 的 Word 文档,其中包含了标题、章节标题

# 打开文档
doc = docx.Document('Sample.docx')
# 打印文档中所有段落的文本内容
for para in doc.paragraphs:
    print(para.text)

读取word中一级标题

import docx
def read_word_title(file_path):
    doc = docx.Document(file_path)
    titles = []
    for paragraph in doc.paragraphs:

        if paragraph.style.name == 'Heading 1':
#            print(paragraph.text)
            titles.append(paragraph.text)
    return titles

file_path = '22.docx'
titles = read_word_title(file_path)
print(titles)

for paragraph in doc.paragraphs:
    print(paragraph.style)  ##可以加个断点,然后debug模式运行,就知道都有什么属性
    print(paragraph.style.style_id)  #Lv10
    print(paragraph.style.base_style.name) #Heading 1
    

在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

在word中打印字体为红色

from docx import Document
import docx
from docx.shared import RGBColor
doc = Document(file_name)
redText=[]
for i in doc.paragraphs:
    for r in i.runs:
        if r.font.color.rgb == docx.enum.text.WD_COLOR_INDEX.RED:
            redText.append(r.text)

print("".join(redText).strip())

或者:
MAX_RED_COLOR = RGBColor(255, 0, 0)
if r.font.color.rgb == MAX_RED_COLOR:
            redText.append(r.text)

加粗字体:
boldText=[]
for i in doc.paragraphs:
    for r in i.runs:
        if r.bold:
            boldText.append(r.text)
# 获取一级标题
for paragraph in paragraphs:
    if paragraph.style.name == 'Heading 1':
        print(paragraph.text)
        # 这是一级标题

有的内容没有stytle.name,可以通过debug运行方式,先看下paragraphy.stytle都有什么属性
# 获取二级标题
for paragraph in paragraphs:
    if paragraph.style.name == 'Heading 2':
        print(paragraph.text)
        # 这是二级标题

# 获取正文
for paragraph in paragraphs:
    if paragraph.style.name == 'Normal':
        print(paragraph.text)



############
import os
import re
from docx import Document

file_name = './5.ceshi.docx'
doc = Document(file_name)
basename = os.path.splitext(os.path.basename(file_name))[0]
print("basename:",basename)  #打印文件名,不包含路径名字

for paragraph in doc.paragraphs:
#    print(paragraph.style)  ###可以debug看下结构
    if "Lv" in paragraph.style.style_id:
        print(paragraph.style.style_id," : ",paragraph.text)  ##打印标题标题内容,对照word,看下每个章节号属于哪个级别目录
        print()  ##换行

pyinstaller 转exe

可将脚本.py文件打包为.exe可执行文件: pip install pyinstaller && pyinstaller -F test.py

完成之后,文件夹里有个dist文件夹,里面就有test.exe可执行文件了
.\test.exe -i "%1" -o 2.txt  将文档保存为.bat批处理文件

封装完之后,可以双击打开,或者在cmd下执行.\test.exe
如果需要输入参数是中文,执行.\test.exe之前加上chcp 936;否则可能乱码
在这里插入图片描述

doc与docx相互转换

DOC是Microsoft Word早期版本(如Office 97及更早)使用的二进制格式,依赖于复杂的BIFF (Binary Interchange File Format)。
DOCX则是Word 2007及其以后版本引入的新标准,基于开放XML(Open XML)规范,支持跨平台阅读和编辑。

python 批量转换docx只转换了一个出现pywintypes.com_error被调用的对象已与其客户端断开连接
pywintypes.com_error: (-2147417848, ‘被调用的对象已与其客户端断开连接。’, None, None)
解决方案: word.Quit() 不要这个

1. 转换doc为docx

#####将当前路径下doc
# -*- coding:utf-8 -*-
import os
import re
from win32com import client

Current_path = os.path.dirname(os.path.abspath(__file__))
Current_path_File = os.listdir(Current_path)

def doc2docx(fn):
    word = client.Dispatch("Word.Application") # 打开word应用程序
    doc = word.Documents.Open(fn)
    doc.SaveAs("{}x".format(fn), 12)
    doc.Close()
    return
    
for file_name in Current_path_File:
    match = re.search("\.doc$", file_name)
    # if match is found
    if match:
        File_path = os.path.join(Current_path, file_name)
        doc2docx(File_path)

2. 转换doc为docx

# 开发时间 3/21/2024 10:24 AM
# -*- coding:utf-8 -*-
import os
import re
from win32com import client

Current_path = os.path.dirname(os.path.abspath(__file__))
Current_path_File = os.listdir(Current_path)

#转换docx为doc
def docx2doc(fn):
    word = client.Dispatch("Word.Application") # 打开word应用程序
    #for file in files:
    doc = word.Documents.Open(fn) #打开word文件
    doc.SaveAs("{}".format(fn[:-1]), 0)#另存为后缀为".docx"的文件,其中参数0指doc
    doc.Close() #关闭原来word文件
#     word.Quit()

for file_name in Current_path_File:
    match = re.search("\.docx$", file_name)
    # if match is found
    if match:
        File_path = os.path.join(Current_path, file_name)
        docx2doc(File_path)

如果想转换为其他格式文件,需要在format文件名内修改,并用如下save as 参数
在这里插入图片描述

如docx转换为pDf,用如下语句:
doc.SaveAs(“{}.pdf”.format(fn[:-5]), 17)

常用函数

常见问题

1 在windows执行报错

AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: ‘charmap’ codec can’t encode characters in position 295-297: character maps to

原因是: 因为你要处理的包含其他字符,如中文、日文等
需要对正确的字符集进行编码,Python 将其识别为 cp850 - Windows 控制台默认值。
解决方案:从 Python 3.4 开始,您可以通过在命令提示符处发出以下命令将 Windows 控制台设置为使用 UTF-8: 在dos命令中输入:chcp 65001

2 在windows执行报错

[WinError 206] The filename or extension is too long
[WinError 3] The system cannot find the path specified:
解决方案:
win+R----->regedit打开注册表
修改注册表中 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem 下的 LongPathsEnabled 的值,从默认值 0 修改为 1

python 常用法

查找字符串是否包含另一个字符串

使用in运算符或str.find()

str1="ddddddddddddddddsheiwefenglish"
if "english" in str1:
    print("found English")

if str1.find("english") != -1:
    print("found English")

##对于不区分大小写:将所有字符串转换为大写或小写
if str1.upper().find("ENGLISH") != -1:
    print("found English")

操作mysql数据库

db = pymysql.connect('localhost','root','123456','maoyandb')

参数说明:
localhost:本地 MySQL 服务端地址,也可以是远程数据库的 IP 地址。
root:连接数据所使用的用户名。
password:连接数据库使用的密码,本机 MySQL 服务端密码“123456”。
db:连接的数据库名称。
# -*-coding:utf-8-*-
import pymysql
#创建对象
db = pymysql.connect('localhost','root','123456','maoyandb')
cursor = db.cursor()  ##创建cursor对象
# sql语句执性,单行插入
info_list = ['刺杀,小说家','雷佳音,杨幂','2021-2-12']
sql = 'insert into movieinfo values(%s,%s,%s)'
#列表传参
cursor.execute(sql,info_list)  #execute() 方法用来执行 SQL 语句
db.commit()
# 关闭
cursor.close()
db.close()

#########二
import pymysql
 
# 建立与MySQL服务器的连接
conn = pymysql.connect(host='localhost', user='root', password='password', database='mydatabase')
cursor = conn.cursor()
 
try:
    # 执行SQL语句
    sql = "SELECT * FROM mytable"
    cursor.execute(sql)
    # 获取所有结果
    results = cursor.fetchall()
    for row in results:
        print(row)
        
except Exception as e:
    print("Error:", str(e))
finally:
    # 关闭连接
    cursor.close()
    conn.close()

类之间函数调用

class 类名:
    多个(≥0)类属性...
    多个(≥0)类方法...

__init__() 方法可以包含多个参数,但必须包含一个名为 self 的参数,且必须作为第一个参数。也就是说,类的构造方法最少也要有一个 self 参数。

class TheFirstDemo:
    '''这是一个学习Python定义的第一个类'''
    #构造方法
    def __init__(self):
        print("调用构造方法")
    # 下面定义了一个类属性
    add = 'http://c.biancheng.net'
    # 下面定义了一个say方法
    def say(self, content):
        print(content)

类创建,在创建类对象时,无需给 self 传参即可
self介绍

class CLanguage:
    '''这是一个学习Python定义的一个类'''
    def __init__(self,name,add):
        print(name,"的网址为:",add)
#创建 add 对象,并传递参数给构造函数
add = CLanguage("C语言中文网","http://c.biancheng.net") ##参数是传给name和add

```python

class Student():
    school = 'JiaLiDun University' # 类中的静态变量,为所有的对象所共有,使用(类名.变量)调用
    def __init__(self, no, name, age):
        self.no = no
        self.name = name
        self.age = age
    def show(self):
        str = self.no + ' ' + self.name + ' ' + self.age + ' ' + Student.school # 类中的静态变量,使用(类名.变量)调用
        print(str)
    def function(self):
        print("显示该生的基本信息如下:")
        # 方法一:self.方法名(参数列表)
        self.show()
        # 方法二:类名.方法名(self, 参数列表)
        Student.show(self)

if __name__ == '__main__':
    student_1 = Student('001', '张三', '20')
    student_2 = Student('002', '李四','22')
    student_1.function()
    student_2.function()

func(*args, **kwargs)

*args 表示将参数作为一个元组(tuple)传递给函数。它允许你传递任意数量的位置参数给函数,这些参数会被打包成一个元组传递给函数内部。函数内部可以使用 args 来访问这个元组,并对其中的参数进行操作。

**kwargs 表示将参数作为一个字典(dict)传递给函数。它允许你传递任意数量的关键字参数给函数,这些参数会被打包成一个字典传递给函数内部。函数内部可以使用 kwargs 来访问这个字典,并对其中的参数进行操作。

def example_func(*args, **kwargs):
    print("位置参数:")
    for arg in args:
        print(arg)
    
    print("关键字参数:")
    for key, value in kwargs.items():
        print(key, value)

# 传递位置参数和关键字参数
example_func(1, 2, 3, name="John", age=25)


位置参数:  1,2,3 传递给args
1
2
3
关键字参数: 字典传递给kwargs
name John
age 25

装饰器

用于在不修改原始函数或类代码的情况下,对其进行功能扩展或修改。装饰器基于函数式编程的概念,通过将函数作为参数传递给另一个函数,并返回一个新的函数来实现。
装饰器常用于以下场景:

  • 添加日志记录
  • 计时统计
  • 输入验证和修正
  • 缓存结果
  • 权限验证
  • 错误处理
    使用@符号紧跟在函数定义的上方,表示将函数装饰为另一个函数。
#########装饰器模板
def decorator(func):
    def wrapper(*args, **kwargs):
        # 在调用原始函数之前执行的操作
        print("执行装饰器前操作")
        # 调用原始函数
        result = func(*args, **kwargs)
        # 在调用原始函数之后执行的操作
        print("执行装饰器后操作")
        # 返回原始函数的结果
        return result
    return wrapper

# 应用装饰器
@decorator  ###装饰函数
def my_function():  ##被装饰函数
    print("原始函数")

# 调用装饰后的函数
my_function()


###结果输出:
执行装饰器前操作
原始函数
执行装饰器后操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值