Mosh大神Python教程学习笔记

基于bili此视频

安装python

安装python和pycharm,创建项目,创建文件,

print语句

1
2
3
4
print("Mosh Hamedani")  # 字符串变量,用`‘`或`“`都可以;
print('o----')
print(' ||||')
print('*'*10) # *10就是乘以搞10个,很形象

结果

1
2
3
4
Mosh Hamedani
o----
||||
**********

变量

1
2
3
4
price = 10  # 整数int
rating = 4.9 # 浮点float
name = 'Mosh' # 字符串string
is_published = False # 布尔bool,为True或False,首字母大写;

例子:定义三个变量,患者姓名、年龄、是否新患者

1
2
3
full_name = 'John Smith'
age = 20
is_new = True

input语句

1
2
name = input('What is your name? ')
print('Hi ' + name) # 字符串连接

例子:输入姓名和喜欢的颜色,输出XXX likes xxx

1
2
3
name = input('What is your name? ')
favorite_color = input('What is your favorite color? ')
print(name + ' likes ' + favorite_color)

类型转换

1
2
3
4
5
int()
float()
bool()
str()
type()

以上为转换和显示类型函数

1
2
3
birth_year = input('Birth year: ')
age = 2022 - birth_year
print(age)

运行报错

1
2
3
4
5
6
7
Birth year: 1985
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 2, in <module>
age = 2022 - birth_year
TypeError: unsupported operand type(s) for -: 'int' and 'str'

进程已结束,退出代码1

因为,输入的1985被认为是字符串变量,int减string出错,需要先将string转换成int;可使用int函数转换,可使用type函数显示类型

1
2
3
4
5
birth_year = input('Birth year: ')
print(type(birth_year))
age = 2022 - int(birth_year)
print(type(age))
print(age)

结果

1
2
3
4
Birth year: 1985
<class 'str'>
<class 'int'>
37

例子:输入磅数,输出公斤;

1
2
3
weight_lbs = input('Weight (lbs): ')
weight_kg = float(weight_lbs) * 0.45
print(weight_kg)

字符串string

单双引号组合:

1
2
course = "Python's Course for Beginners"
print(course)
1
2
course = 'Python for "Beginners"'
print(course)

三引号,实现多行字符串,比如邮件

1
2
3
4
5
6
7
8
9
10
course = """
Hi John

Here is out first email to you.

Thank you,
The support team

"""
print(course)

字符串索引,方括号的使用

1
2
3
4
5
6
7
8
9
10
11
course = 'Python for Beginners'
# 0123456789
print(course[0])
print(course[1])
print(course[-1])
print(course[-2])
print(course[0:3])
print(course[1:])
print(course[:5])
print(course[:])
print(course[1:-1])

输出

1
2
3
4
5
6
7
8
9
P
y
s
r
Pyt
ython for Beginners
Pytho
Python for Beginners
ython for Beginner

转义字符 \

格式化字符串

1
2
3
4
5
6
first = 'John'
last = 'Sminth'
message = first + ' [' + last + '] is a coder'
msg = f'{first} [{last}] is a coder'
print(message)
print(msg)

主要是f函数和花括号的使用

字符串用法

1
2
3
4
5
6
7
8
9
10
11
12
13
course = 'Python for Beginners'
print(len(course))
print(course)
print(course.upper())
print(course.lower())
print(course.title())
print(course.find('o'))
print(course.find('0'))
print(course.find('Beginners'))
print(course.replace('Beginners','Absolute Beginners'))
print(course.replace('P','J'))
print('Python' in course)
print(course)

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
20
Python for Beginners
PYTHON FOR BEGINNERS
python for beginners
Python For Beginners
4
-1
11
Python for Absolute Beginners
Jython for Beginners
True
Python for Beginners

进程已结束,退出代码0

熟悉常见函数

1
2
3
4
5
6
7
8
course = 'Python for Beginners'
len(course)
course.upper()
course.lower()
course.title()
course.find()
course.replace()
'...' in course

算术运算

1
2
3
4
5
6
7
8
9
10
11
print(10 / 3)
print(10 // 3)
print(10 % 3)
print(10 ** 3)
x = 10
x = x + 3
print(x)
x += 3
print(x)
x -= 3
print(x)

结果

1
2
3
4
5
6
7
3.3333333333333335
3
1
1000
13
16
13

运算符优先级

1
2
3
4
5
6
7
8
x = 10 +3 *2
print(x)
x = 10 +3 *2 ** 2
print(x)
x = (10 +3) *2 ** 2
print(x)
x = (2 +3) *10 - 3
print(x)

结果

1
2
3
4
16
22
52
47

数学函数

1
2
3
4
5
6
x = 2.1
print(round(x)) # 取整
print(abs(-x)) # 绝对值
import math
print(math.ceil(x)) # 向上取整
print(math.floor(x)) # 向下取整

结果

1
2
3
4
2
2.1
3
2

If语句

1
2
3
4
5
6
7
8
9
10
11
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day" )
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")

练习:

1
2
3
4
5
6
7
8
price = 1000000
has_good_credit = False

if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f"Down payment:{down_payment}")

逻辑运算符

1
2
3
4
5
6
has_high_income = True
has_good_credit = True
has_criminal_record = False

if has_high_income and has_good_credit and not has_criminal_record:
print("Eligible for loan")

and or not的使用

比较运算符

1
2
3
4
5
temperature = 30
if temperature > 30:
print("it's a hot day")
else:
print("It's not a hot day")
1
2
3
4
5
6
7
8
name = "J"
print(len(name))
if len(name) < 3:
print("Name must be at least 3 character")
elif len(name) >50:
print("Name must be a maximum of 50 character")
else:
print("Name looks good!")

(练习)重量转换

1
2
3
4
5
6
weight = input("Weight: ")
lbs_or_kg = input("(L)bs or (k)g: ")
if lbs_or_kg.upper() == "L":
print(f"You are {float(weight)*0.45} kilos")
elif lbs_or_kg.upper() == "K":
print(f"You are {float(weight)/0.45} pounds")

while循环

1
2
3
4
5
i = 1
while i <= 5:
print("*" * i)
i += 1
print("Done")

结果

1
2
3
4
5
6
*
**
***
****
*****
Done

(练习)制作猜谜游戏

1
2
3
4
5
6
7
8
9
10
11
secrets_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess =int(input("Guess: "))
guess_count += 1
if guess == secrets_number:
print("You win")
break
else:
print("Sorry,you failed")

(练习)汽车游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
command = ""
started = False
while True: #while command !=quit作用一样
command = input(">").lower()
if command == "help":
print("""
start - to start the car
stop - to stop the car
quit - to exit
""")
elif command == "start":
if started:
print("Car is already started")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("Car is already stopped.")
else:
started = False
print("Car stopped")
elif command == "quit":
break
else:
print("sorry,I don't understand that")

23 for循环

用for循环便利字符串

1
2
3
4
5
6
7
8
9
10
11
12
for item in "Python":
print(item)
for item in ["Mosh",'John','Samzz']:
print(item)
for item in [1,2,3,4]:
print(item)
for item in range(10):
print(item)
for item in range(5,10):
print(item)
for item in range(5,10,2):
print(item)

range函数语法

1
range(start, stop[, step])

参数说明:

  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

例子,计算购物车里所有产品价格综合

1
2
3
4
5
prices = [10,20,30]
total = 0
for price in prices:
total += price
print(f"Total: {total}")

24 嵌套循环

用(x,y)坐标理解循环嵌套

1
2
3
for x in range(4):
for y in range(3):
print(f"({x},{y})")

结果

1
2
3
4
5
6
7
8
9
10
11
12
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)

例子,打印x组成的F图形

1
2
3
4
5
XXXXX
XX
XXXXX
XX
XX

代码如下,这不都是初高中学basic和pascal时候的练习题么,哎………………

1
2
3
4
5
6
numbers = [5,2,5,2,2]
for x in numbers:
output = ""
for y in range(x):
output = output + "x"
print(output)

25 列表

1
2
3
4
5
6
7
8
9
10
names = ['John','Bob','Sam','Jack','lisa','Google']
print(names)
print(names[0])
print(names[1])
print(names[-1])
print(names[1:])
print(names[1:3])
print(names[:])
names[0] = 'Joh'
print(names)

看看结果感觉下

1
2
3
4
5
6
7
8
['John', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']
John
Bob
Google
['Bob', 'Sam', 'Jack', 'lisa', 'Google']
['Bob', 'Sam']
['John', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']
['Joh', 'Bob', 'Sam', 'Jack', 'lisa', 'Google']

例子,找出列表中的最大数

1
2
3
4
5
6
numbers = [1,9,2,5,7,8,0,7,11,87,99,43,12,41]
max = numbers[0]
for number in numbers:
if number > max :
max = number
print(max)

最初编写的时候,多用了一个count函数,为了取数number[count],看了教程代码才发现,for number in出来的number就是列表里的数字,方便多了不是

26 二维列表

1
2
3
4
5
6
7
8
9
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix)
matrix[0][2] = 30
print(matrix[0][2])
print(matrix[0])

认识下二维列表和用法

二维列表的遍历

1
2
3
4
5
6
7
8
9
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in matrix:
print(row)
for item in row:
print(item)

看看结果

1
2
3
4
5
6
7
8
9
10
11
12
[1, 2, 3]
1
2
3
[4, 5, 6]
4
5
6
[7, 8, 9]
7
8
9

28 列表函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
numbers = [3,4,5,8,5,4]
numbers.append(20) # 末尾增加
print(numbers)
numbers.insert(0,10) # 指定位置插入
print(numbers)
numbers.remove(8) # 删除指定值,只能删除第一个
print(numbers)
numbers.pop() # 删除末尾
print(numbers)
print(numbers.index(3)) # 索引内容不在列表中会出错,可以用下面的in
print(50 in numbers) # 索引返回布尔值
print(numbers.count(5)) # 计数
numbers.sort() # 排序,由小到大
print(numbers)
numbers.reverse() # 反序
print(numbers)
numbers.clear() # 清除值
print(numbers)

列表去重,方法牛鼻,原本以为是嵌套循环来比较,没想到这么简单,

1
2
3
4
5
6
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)

结果

[2, 4, 6, 3, 1]

29 元组

可以理解为不能修改的列表,用(),因为不能修改所以元组的函数很少,就计数和索引;用于不需修改的值

1
2
3
4
numbers = (2,4,6,1,2)
print(numbers[1])
print(numbers.count(2)) # 计数
print(numbers.index(1)) # 索引

30 拆包

1
2
3
numbers = [1,2,3]
x,y,z = numbers
print(x,y,z) # 不是必须一起打印,单个打印也没问题

拆包的好处是,不用每次都写那么长的函数,用起来方便,另外列表和数组都可以拆包

31 字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
customer ={
"name": "Sam Zz",
"age": 36,
"is_man" : True
}
print(customer) # 注意显示方式
print(customer["name"]) # 取值,取不存在的值会报错
print(customer.get("name")) # get取值
print(customer.get("birthday")) # get取到不存在的值返回none
print(customer.get("birthday","123")) # 第二个值是默认值,当get取值存在时返回取值,当get取值不存在时返回默认值,但不改变原有字典
print(customer)
customer["name"]="Jack Smith" # 修改值
print(customer["name"])
customer["birthdate"]="Jan 1 1980" # 没有的值则为添加
print(customer)

看看运行结果

1
2
3
4
5
6
7
8
9
10
{'name': 'Sam Zz', 'age': 36, 'is_man': True}
Sam Zz
Sam Zz
None
123
{'name': 'Sam Zz', 'age': 36, 'is_man': True}
Jack Smith
{'name': 'Jack Smith', 'age': 36, 'is_man': True, 'birthdate': 'Jan 1 1980'}

进程已结束,退出代码0

例子,输入电话号码,翻译成英文,输入1234,输出One Two Three Four

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
phone = input("Phone: ")
digits_mapping = {
"1":"One",
"2":"Two",
"3":"Three",
"4":"Four",
"5":"Five",
"6":"Six",
"7":"Seven",
"8":"Eight",
"9":"Nine",
"0":"Zero"
}
output = ""
for ch in phone: # 字符串的for简直不要太好用
output += digits_mapping.get(ch,"!") + " " # 这里的!是,如果输入字符不在字典里就输出默认值!,巧妙;更巧妙的是!=后面还能加,优秀
print(output)

字符串的for简直不要太好用,过去编程这种情况还需要先 统计字符串长度x,然后从0到x循环来一个一个取数判断,累屁了,python太方便了

结果

1
2
Phone: 15612345678
One Five Six One Two Three Four Five Six Seven Eight
1
2
Phone: +86123456
! Eight Six One Two Three Four Five Six

32 表情转换器

输入表情字符变表情,例如输入Good morning sunshine :)变成Good morning sunshine 😁 ,windows版添加表情是win键+;

1
2
3
4
5
6
7
8
9
10
11
message = input(">")  # 输入的是字符串,要先分拆,按空格分割比较科学
words = message.split(' ') # 分拆函数,按照空格分割并存储为列表,牛鼻牛鼻
print(words) # 验证拆分
emojis = { # 映射表情字符的字典
":)": "😁",
":(": "😒"
}
output = ""
for word in words:
output += emojis.get(word, word) + " " # 此处又牛鼻了,get取数,不存在的值设默认值为原值
print(output)

结果

1
2
3
>Good morning sunshine :)
['Good', 'morning', 'sunshine', ':)']
Good morning sunshine 😁
1
2
3
>I am sad :(
['I', 'am', 'sad', ':(']
I am sad 😒

33 函数

1
2
3
4
5
6
7
8
9
def greet_user():  # 定义函数
print("Hi there!")
print("Welcome aboard")


# pep8的代码规范是在函数后要空两行
print("Start")
greet_user() # 调用函数
print("Finish")

重复功能定义函数,让代码更简洁

1
2
3
4
Start
Hi there!
Welcome aboard
Finish

34 参数

函数增加参数

1
2
3
4
5
6
7
8
9
def greet_user(name):  # 函数增加一个参数
print(f"Hi {name}!")
print("Welcome aboard")


print("Start")
greet_user("Samzz") # 调用函数必须带参数的值,否则出错
greet_user("Jack")
print("Finish")

增加两个参数

1
2
3
4
5
6
7
8
9
def greet_user(first_name,last_name):
print(f"Hi {first_name} {last_name}!")
print("Welcome aboard")


print("Start")
greet_user("Sam","Zz")
greet_user("Jack","Chen")
print("Finish")

此种方法为位置参数,要注意位置顺序;

结果

1
2
3
4
5
6
Start
Hi Sam Zz!
Welcome aboard
Hi Jack Chen!
Welcome aboard
Finish

35 关键字参数

1
2
3
4
5
6
7
8
9
def greet_user(first_name,last_name):
print(f"Hi {first_name} {last_name}!")
print("Welcome aboard")


print("Start")
greet_user("Sam",last_name="Zz") # 位置参数和关键字参数混合使用必须位置参数在前,如位置参数在关键字参数后会报错
greet_user(first_name="Jack",last_name="Chen") # 全部使用关键字参数
print("Finish")

关键字参数一半用于多个参数的值不好分辨时,比如三个三处都是数字,代码可读性差,增加关键字参数增加代码可读性

结果

1
2
3
4
5
6
Start
Hi Sam Zz!
Welcome aboard
Hi Jack Chen!
Welcome aboard
Finish

36 返回语句

函数需要返回值,用return即可,平方函数

1
2
3
4
5
def square(number):
return (number * number)


print(square(3))

37 创建可重复使用的函数

将32的表情转换改为函数

1
2
3
4
5
6
7
8
9
10
11
12
13
def emoji_converter (message):
words = message.split(' ')
emojis = {
":)": "😁",
":(": "😒"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output

message = input(">")
print(emoji_converter(message))

注意函数内的message变量和函数外的message变量是两个变量,名字不同亦可,各自有各自的使用区间,函数内的仅在函数内有效,函数外的仅在函数外有效;

38 例外

输入输出年龄

1
2
age = int (input('Age: '))
print(age)

如果输入不是数字,无法int,则报错

1
2
3
4
5
Age: asd
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 1, in <module>
age = int (input('Age: '))
ValueError: invalid literal for int() with base 10: 'asd'

错误类型为ValueError,正常程序中避免出错中断会把错误排除或提示出来让程序继续,所以用例外

1
2
3
4
5
try:
age = int (input('Age: '))
print(age)
except ValueError:
print('Invalid value')

结果

1
2
Age: aaa
Invalid value

延生,年龄不能为0

处理0可以用数除以0报错,例外这个报错;

1
2
3
4
5
6
try:
age = int (input('Age: '))
risk = 1/age
print(age)
except ValueError:
print('Invalid value')

结果

1
2
3
4
5
Age: 0
Traceback (most recent call last):
File "D:\Python\15\HelloWorld\app.py", line 3, in <module>
risk = 1/age
ZeroDivisionError: division by zero

报错为ZeroDivisionError,把这个错误也排除掉;

这种用if语句也能判断,难道用例外更简单?

1
2
3
4
5
6
7
8
try:
age = int (input('Age: '))
risk = 1/age
print(age)
except ZeroDivisionError:
print('Age cannot be 0.')
except ValueError:
print('Invalid value.')
1
2
Age: 0
Age cannot be 0.

39 注释

1
# 一个#一个空格开始注释

老师的观念是能读懂的代码别再注释,这要拿捏了

40 类 class

1
2
3
4
5
6
7
8
9
10
11
12
class Point:
def move(self):
print('move')
def draw(self):
print('draw')


point1 = Point()
point1.x = 10
print(point1)
print(point1.x)
point1.draw()

类名首字母为大写,point1叫做实例(和云计算里面的叫法一样啊)

41 类的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def move(self):
print('move')
def draw(self):
print('draw')


point1 = Point(10,20)
print(point1.x)

大概理解了

例子,创建Person类,包含name和talk,name为构造函数

1
2
3
4
5
6
7
8
9
10
11
class Person:
def __init__(self,name):
self.name = name
def talk(self):
print(f'Hi, I am {self.name}')


john = Person('John Smith')
john.talk()
samzz = Person('Sam Zz')
samzz.talk()

创建john和samzz两个Person类的实例

结果

1
2
Hi, I am John Smith
Hi, I am Sam Zz

42 继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Mammal:
def walk(self):
print('walk')


class Dog(Mammal): # 类的继承,继承了父类的函数
def bark(self): # 继承后定义自己的函数
print('bark')


class Cat(Mammal): # 类的继承
pass

dog1 = Dog()
dog1.bark()
dog1.walk()
cat1 = Cat()
cat1.walk()

结果

1
2
3
bark
walk
walk

43 模块 module

import导入其他py文件,省略py

例子:重量单位转换文件convertres.py

1
2
3
4
5
6
def lbs_to_kg(weight):
return weight * 0.45


def kg_to_lbs(weight):
return weight / 0.45

在app.py中导入,两种导入方法,一种是全部导入,一种是导入其中的函数

1
2
3
4
5
6
7
import converters  # 全部导入

print(converters.kg_to_lbs(70)) # 使用函数的方法.

from converters import kg_to_lbs # 导入其中函数

print(kg_to_lbs(70)) # 直接使用函数

例子:将25列表里的寻找最大值变成模块

建立utils.py文件,入参为列表,返回最大值

1
2
3
4
5
6
7
def find_max(numbers):
#
max = numbers[0]
for number in numbers:
if number > max :
max = number
return (max)

app.py中导入utils,两种导入和调用函数的方法

1
2
3
4
5
6
7
8
import utils

numbers = [1, 9, 2, 5, 7, 8, 0, 7, 11, 87, 99, 43, 12, 41]
print(utils.find_max(numbers))

from utils import find_max

print(find_max(numbers))

结果

1
2
99
99

44 包

项目中新建一个包(或者创建一个文件夹、文件夹里创建一个__init__.py的文件),推荐直接创建一个包

在包里创建一个shipping.py文件

1
2
def calc_shipping():
print('calc_shipping')

在主文件app.py中导入包中的模块中的函数,三种方法

1
2
3
4
5
6
7
8
import ecommerce.shipping
ecommerce.shipping.calc_shipping()

from ecommerce.shipping import calc_shipping
calc_shipping()

from ecommerce import shipping
shipping.calc_shipping()

第一种是导入包的模块,第二种是导入包中模块中的函数,第三种是导入包中的模块,导入不同使用函数式写法不同,第二种写法最简单,三种结果都一样

1
2
3
calc_shipping
calc_shipping
calc_shipping

45 生成随机数(使用random函数)

random函数需要先导入模块,random功能强大,以下是生成随机数、生成10-20的随机数、在列表里随机选择一个三种使用

1
2
3
4
5
6
7
8
9
10
11
12
import random


for i in range(3):
print(random.random()) # 生成随机数

for i in range(3):
print(random.randint(10,20)) #10-20间随机数

numbers = ['Sam','John','Mary','Jack']
leader = random.choice(numbers) # 列表里随机选择
print(leader)

例子:掷色子,两颗,即同时生成两个随机数,用到了类和随机数函数

1
2
3
4
5
6
7
8
9
10
11
12
import random


class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second


dice = Dice()
print(dice.roll())

结果

(5, 3)

随机数,每次运行结果都不一定相同

46 使用目录

Path.glob搜索目录下的文件

1
2
3
4
from pathlib import Path

path = Path()
print(path.glob('*.py'))

运行后提示

<generator object Path.glob at 0x0000022A3E6D1D20>

为生成器对象存在内存中,需要循环遍历生成器对象,而不是打印,所以修改

1
2
3
4
5
from pathlib import Path

path = Path()
for file in path.glob('*.py'):
print(file)

或者

1
2
3
4
5
import pathlib

path = pathlib.Path()
for file in path.glob('*.py'):
print(file)

结果

1
2
3
4
app.py
converters.py
main.py
utils.py

47 pypi 和 pip

pypi.org是python官方的第三方库的仓库,供用户下载第三方库,也供开发这上传自己开发的库;

pip是python的包管理工具,全名python install packages;

视频讲了常用的处理excel的包openpyxl,安装openpyxl

cmd或者终端pip install openpyxl,稍等即可完成安装

48 项目1:使用python实现自动化(excel的操作)

先做这步,不然写完代码运行提示没有openpyxl的模块

https://blog.51cto.com/u_15080034/4160083

项目里的excel下载地址https://github.com/RagingLeviathan/HelloWorld-mosh-python/raw/master/transactions.xlsx

读excel里的值

1
2
3
4
5
6
7
8
9
10
11
12
13
import openpyxl as xl # 别名,方便使用
wb = xl.load_workbook('transactions.xlsx') # load文件
sheet = wb['Sheet1']

print(sheet.cell(1,1).value) #一种方法
cell = sheet['b1'] #单元格
cell1 = sheet.cell(1,3) #单元格
print(cell.value) #打印单元格值
print(cell1.value)
print(sheet.max_row) #最大行
print(sheet.min_row)
print(sheet.max_column) #最大列
print(sheet.min_column)

例子:打印表里price列的值,循环从c2开始(c1是表头)到c4(max_row+1,因为到max_row是2到4不包含4,所以+1)

1
2
3
4
5
6
7
8
import openpyxl as xl
wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']

# 输出表里price的值
for row in range(2,sheet.max_row+1):
cell =sheet.cell(row,3)
print(cell.value)

结果

1
2
3
5.95
6.95
7.95

列子:讲price*0.9生成新价格写入文件

1
2
3
4
5
6
7
8
9
10
11
12
import openpyxl as xl

wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

wb.save('t.xlsx') # 写入文件

运行完找到t.xlsx文件即可看到写入的内容

例子:创建图标表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import openpyxl as xl
from openpyxl.chart import BarChart,Reference

wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

values = Reference(sheet,
min_row=2,
max_row=sheet.max_row,
min_col=4,
max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart,'e2')

wb.save('t.xlsx') # 写入文件

将D2-D4的数据生成图标,写入t.xlsx中

例子:将以上程序改为函数,实现时调用函数即可做多文件的自动化执行

改造后的样子(程序处理完后在原文件里修改了)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import openpyxl as xl
from openpyxl.chart import BarChart, Reference


def process_workbook(filename):
wb = xl.load_workbook(filename)
sheet = wb['Sheet1']
# 输出C2-C4的位置到cell,cell的值*0.9给到new_price,保存到D2-D4
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price

values = Reference(sheet,
min_row=2,
max_row=sheet.max_row,
min_col=4,
max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'e2')

wb.save(filename) # 写入文件

process_workbook('transactions2.xlsx')

如果有一堆表格,处理的地方一样,用上面的文件遍历,再调用函数就能实现;实际问题中还是很复杂的。

后面两课机器学习和Django制作网站时长特别长,慢慢学习吧,这个十一先学这些。