1.画一个正放形
import turtle
turtle.pensize(4)
turtle.pencolor('black')
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.mainloop()
2.将华氏温度转换成摄氏温度
f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))
3. 字符a与97的转换,97与字符a的转换
print(ord("a"))
print(chr(97))
4. 闰年判断
year = int(input('请输入年份: '))
is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0
print(is_leap)
5. 用户名和密码验证
username = input('请输入用户名: ')
password = input('请输入口令: ')
if username == 'admin' and password == '123456':
print('身份验证成功!')
else:
print('身份验证失败!')
6. if语法并且输出结果显示格式为带2位小数的浮点数
x = float(input("请输入x:"))
if x>1:
y = 3*x-5
elif -1<=x<=1:
y=x+2
elif x<-1:
y=5*x+3
print("f(x)=%.2f" % y)
7. 英寸和厘米之间的转换
value = float(input('请输入长度: '))
unit = input('请输入单位: ')
if unit == 'in' or unit == '英寸':
print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
print('%f厘米 = %f英寸' % (value, value / 2.54))
else:
print('请输入有效的单位')
8. 从1加到100
sum=0
for i in range(1,101):
sum+=i
print(sum)
9.产生1到100的随机数
import random
answer = random.randint(1, 100)
10.判断一个数是不是素数
from math import sqrt
num = int(input('请输入一个正整数: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print('%d是素数' % num)
else:
print('%d不是素数' % num)
11.生成9*9乘法表
for i in range(1,10):
for j in range(1,10):
print("%d*%d=%d"%(i,j,i*j),end="\t")
print()
row = 1
while row<=9:
col =1
while col<=row:
print("%d*%d=%d\t"%(col,row,col*row),end="")
col+=1
print("")
row+=1
12.字符串操作函数
s1 = 'hello ' * 3
print(s1)
s2 = 'world'
s1 += s2
print(s1)
print('ll' in s1)
print('good' in s1)
12.1字符串切片
str2 = 'abc123456'
print(str2[2])
print(str2[2:5])
print(str2[2:])
print(str2[2::2])
print(str2[::2])
print(str2[::-1])
print(str2[-3:-1])
print(str2.isdigit())
print(str2.isalpha())
print(str2.isalnum())
12.2字符串函数
str1 = 'hello, world!'
num = str1.count("w")
print(num)
print(len(str1))
print(str1.capitalize())
print(str1.title())
print(str1.lower())
print(str1.upper())
print(str1.find('or'))
print(str1.find('shit'))
print(str1.index('or'))
print(str1.startswith('He'))
print(str1.startswith('hel'))
print(str1.endswith('!'))
print(str1.center(50, '*'))
print(str1.rjust(50, ' '))
print(",".join("abc"))
print(":".join(["a","b","c"]))
str3 = ' jackfrued@126.com '
print(str3)
print(str3.strip())
print(str3.split("@"))
print(str3.replace("com","cn"))
print(str3.__contains__("com"))
12.3正则表达式
import re
print(re.findall("\d","nihao123Tianxia"))
print(re.findall("[a-z]","nihao123Tianxia"))
print(re.findall("m","nihao123Tianxia"))
print(re.findall("[0-9]","nihao123Tianxia"))
print(re.findall("[a-zA-z]","nihao123Tianxia"))
print(re.findall("[^0-9]","nihao123Tianxia"))
print(re.findall("x[cw]z","xyz,xcz,xwz"))
print(re.findall("x[^cw]z","xyz,xcz,xwz"))
print(re.findall("\D","nihao123Tianxia"))
print(re.findall("\W","nihao123\nTian\txia"))
print(re.findall("\w","nihao123\nTian\txia"))
print(re.findall("\s","nihao123\nTian\txia"))
print(re.findall("\S","nihao123\nTian\txia"))
print(re.findall("[a-zA-Z]{3,5}","EXCEL 12345world789ppt87lr"))
print(re.findall("[a-zA-Z]{2}","EXCEL 12345world789ppt87lr"))
print(re.findall("excel*","excel 12345world789exce87excellllm"))
print(re.findall("excel+","excel 12345world789exce87excellllm"))
print(re.findall("(excel)","excel 12345world789exce87excellllm"))
print(re.findall("(excel){2}","excelexcel 123excel45world789exce87excellllm"))
print(re.findall("^\d{11}","138111158888b"))
print(re.findall("\d{11}$","138111158888"))
print(re.findall("^\d{11}$","13811115888"))
print(re.findall("(abc)(xyz)","mjqabcxyzjjjabcxyzmmm"))
print(re.findall("JJJ","mjqabcxyzjjjabcxyzmmm",re.I))
print(re.findall("JJJ.{2}","mjqabcxyzjjjabcxyzmmm",re.I))
print(re.findall("JJJ.{2}","mjqabcxyzjjjabcxyzmmm",re.I|re.S))
print(re.findall("b(.*)h","c57892bkj874163hu"))
print(re.search("\d","nihao123Tianxia"))
print(re.search("m","nihao123Tianxia"))
import re
a = "c57892bkj874163hu"
print(re.search("\d",a).group())
import re
a = "c57892bkj874163hu"
print(re.search("\d",a).span())
import re
a = "123abc456789"
r = re.search("([0-9]*)([a-z]*)([0-9]*)",a)
print(r.group())
print(r.group(0))
print(r.group(1))
print(r.group(2))
print(r.group(3))
print(re.split("\d","nihao13Tian2xia"))
print(re.sub("\d","*","nihao123Tianxia"))
print(re.sub("\d","*","nihao123Tianxia",2))
import re
a = "abcFBIabcFBIKJGI"
def nihao(形参):
return "胡启行"
print(re.sub("FBI",nihao,a,1))
import re
a = "abcFBIabcFBIKJGI"
def nihao(形参):
分段获取 = 形参.group()
return "$" + 分段获取 + "$"
print(re.sub("FBI",nihao,a))
import re
a = "c57892bkj874163hu"
def nihao(形参):
分段获取 = 形参.group()
if int(分段获取) >= 5:
return "9"
else:
return "0"
print(re.sub("[0-9]",nihao,a))
12.4遍历字符串
str1 = 'hello, world!'
for char in str1:
print(char)
a, b = 5, 10
print('%d * %d = %d' % (a, b, a * b))
print('{0} * {1} = {2}'.format(a, b, a * b))
print(f'{a} * {b} = {a * b}')
13.list列表
list1 = [1, 3, 5, 7, 100]
list2 = ['hello'] * 3
print(list1.count(3))
print(len(list1))
print(list2)
print(list1[0])
print(list1[4])
print(list1[5])
print(list1[-1])
print(list1[-3])
list1[2] = 300
print(list1)
for index in range(len(list1)):
print(list1[index])
for elem in list1:
print(elem)
for index, elem in enumerate(list1):
print(index, elem)
0 1
1 3
2 300
3 7
4 100
list1.append(200)
print(list1)
list1.insert(1, 400)
print(list1)
list1.extend([1000,2000])
print(list1)
if 3 in list1:
list1.remove(3)
print(list1)
list1.pop(0)
print(list1)
list1.pop(len(list1)-1)
print(list1)
list1.clear()
print(list1)
13.1list列表切片
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits1 = fruits[1:4]
print(fruits1)
fruits2 = fruits[:]
print(fruits2)
fruits3 = fruits[-3:-1]
print(fruits3)
fruits4 = fruits[::-1]
print(fruits4)
13.2list列表排序
list1 = [9, 3, 578, 7, 100]
list2 = sorted(list1)
print(list2)
list1.sort()
print(list1)
list3 = sorted(list1, reverse=True)
print(list3)
list1.reverse()
print(list1)
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
list4 = sorted(fruits, key=len)
print(list4)
13.2list列表遍历,输出1-999的数据的平方值
f = [x for x in range(1, 10)]
print(f)
f = [x + y for x in 'AB' for y in '123']
print(f)
import sys
f = [x ** 2 for x in range(1, 1000)]
print(sys.getsizeof(f))
print(f)
14.元组
tuple = ()
t = ('骆昊', 38, True, '四川成都')
print(t.index("四川成都"))
print(t.count("四川成都"))
print(t[0])
for member in t:
print(member)
t = ('王大锤', 20, True, '云南昆明')
print(t)
person = list(t)
print(person)
person[0] = '李小龙'
print(person)
t1 = tuple(person)
print(t1)
15.集合增加元素
15.1集合增加元素
set1 = {1, 2, 3, 3, 3, 2}
print(set1)
print('Length =', len(set1))
set1.add(4)
set1.add(5)
print(set1)
15.2集合去除元素,生成集合
set2 = set(range(1, 10))
set2.update([11, 12])
set2.discard(5)
print(set2)
if 4 in set2:
set2.remove(4)
print(set2)
set3 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
print(set3)
set4 = {1, 2, 3, 3, 3, 2}
print(set4.pop())
15.3集合交集并集等操作
set1 = {-3,-2,-1,0,1, 2, 3}
set2 = {1, 2, 3, 4, 5, 6}
print(set1 & set2)
print(set1.intersection(set2))
print(set1 | set2)
print(set1.union(set2))
print(set1 - set2)
print(set1.difference(set2))
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
16.字典
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
for key in scores:
print(f'{key}: {scores[key]}')
骆昊: 95
白元芳: 78
狄仁杰: 82
scores['白元芳'] = 65
items1 = dict(one=1, two=2, three=3, four=4)
print(items1)
items2 = dict(zip(['a', 'b', 'c'], '123'))
print(items2)
items3 = {num: num ** 2 for num in range(1, 10)}
print(items3)
print(scores['骆昊'])
scores.update(冷面=67, 方启鹤=85)
if '狄仁杰' in scores:
print(scores['狄仁杰'])
print(scores.get('狄仁杰'))
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
scores.popitem()
print(scores)
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
scores.pop('狄仁杰')
print(scores)
scores.clear()
print(scores)
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
key = scores.keys()
print(key)
value = scores.values()
print(value)
tup = scores.items()
print(tup)
17.日期类
import datetime
import time
print(datetime.date.today())
print(datetime.date(2022,5,18))
print(datetime.date.fromtimestamp(time.time()))
print(datetime.date.min)
print(datetime.date.max)
print(datetime.date.resolution)
d = datetime.date.fromtimestamp(time.time())
print(d.year)
print(d.month)
print(d.day)
print(d.replace(year=2022))
print(d.toordinal())
print(d.weekday())
print(d.isoweekday())
print(d.isoformat())
print(d.strftime("%Y年%m月%d日"))
"""
{}表示占位符 =表示要填充为=号,^表示将后面的内容datetime.time居中对齐,
50表示要填充50个等号,如果有:<表示左对齐,>表示右对齐
"""
print("{:=^50s}".format("datetime.time"))
print("{:=<50s}".format("datetime.time"))
print("{:=>50s}".format("datetime.time"))
18.时间类
import datetime
import time
t = datetime.time(15,10,45,888888)
print(t)
print(datetime.time.min)
print(datetime.time.max)
print(datetime.time.resolution)
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
print(t.isoformat())
print(t.strftime("%H时%M分%S秒 %f微妙"))
import datetime
import time
dt = datetime.datetime(2020,8,20,13,22,34,888888)
print(dt)
print(datetime.datetime.today())
print(datetime.datetime.utcnow())
print(datetime.datetime.fromtimestamp(time.time()))
print(datetime.datetime.utcfromtimestamp(time.time()))
print(datetime.datetime.strptime("2020-06-23 23:15:36","%Y-%m-%d %H:%M:%S"))
d = datetime.date.fromtimestamp(time.time())
t = datetime.time(15,10,45,888888)
print(datetime.datetime.combine(d,t))
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.microsecond)
print(dt.replace(second=57,day=30))
print(dt.timetuple())
print(dt.timestamp())
print(dt.strftime("%Y年%m月%d日 %H时%M分%S秒 %f微妙"))
print(datetime.datetime.fromtimestamp(time.mktime(time.localtime())))
import datetime
td = datetime.timedelta(days=10,hours=5)
print(td)
td = datetime.timedelta(days=-5,hours=-8)
print(td)
td = datetime.timedelta(hours=75)
print(td)
td = datetime.timedelta(weeks=2)
print(td)
19.xlrd库,openpyxl库
19.1读取excel
pip install xlrd==1.2.0
import xlrd
book = xlrd.open_workbook("income.xlsx")
print(f"包含表单数量 {book.nsheets}")
print(f"表单的名分别为: {book.sheet_names()}")
book.sheet_by_index(0)
book.sheet_by_name('2018')
book.sheets()
import xlrd
book = xlrd.open_workbook("income.xlsx")
sheet = book.sheet_by_index(0)
print(f"表单名:{sheet.name} ")
print(f"表单索引:{sheet.number}")
print(f"表单行数:{sheet.nrows}")
print(f"表单列数:{sheet.ncols}")
print(f"单元格A1内容是: {sheet.cell_value(rowx=0, colx=0)}")
print(f"第一行内容是: {sheet.row_values(rowx=0)}")
print(f"第一列内容是: {sheet.col_values(colx=0)}")
incomes = sheet.col_values(colx=1,start_rowx=1)
print(f"2018年总收入为: {sum(incomes)}")
import xlrd
book = xlrd.open_workbook("income.xlsx")
sheet = book.sheet_by_index(0)
toSubstract = 0
monthes = sheet.col_values(colx=0)
for row,month in enumerate(monthes):
if type(month) is str and month.endswith('*'):
income = sheet.cell_value(row,1)
print(month,income)
toSubstract += income
print("带*月份的收入总和是:%2.f" % toSubstract)
import xlrd
book = xlrd.open_workbook("income.xlsx")
book1 =book.sheets()
incomes = 0
toSubstract = 0
toSubstract1 = 0
toSubstract2 = 0
for i in range(0,3):
incomes += sum(book1[i].col_values(colx=1,start_rowx=1))
print(f"三张表的所有收入之和{incomes}")
monthes = book1[0].col_values(colx=0)
for row,month in enumerate(monthes):
if type(month) is str and month.endswith('*'):
income = book1[0].cell_value(row,1)
toSubstract += income
print(f"第0张表结尾带*字符的收入之和{toSubstract}")
monthes1 = book1[1].col_values(colx=0)
for row,month in enumerate(monthes1):
if type(month) is str and month.endswith('*'):
income = book1[1].cell_value(row,1)
toSubstract1 += income
print(f"第1张表结尾带*字符的收入之和{toSubstract1}")
monthes2 = book1[2].col_values(colx=0)
for row,month in enumerate(monthes2):
if type(month) is str and month.endswith('*'):
income = book1[2].cell_value(row,1)
toSubstract2 += income
print(f"第2张表结尾带*字符的收入之和{toSubstract2}")
print(f"三张表总共第一列结尾除去*的收入之和是{incomes-toSubstract-toSubstract1-toSubstract2}")
19.2写入excel
pip install openpyxl
import openpyxl
book = openpyxl.Workbook()
sh = book.active
sh.title = '工资表'
sh1 = book.create_sheet('年龄表-最后')
sh2 = book.create_sheet('年龄表-最前',0)
sh3 = book.create_sheet('年龄表2',1)
sh = book['工资表']
sh['A1'] = '你好'
sh.cell(2,2).value = '白月黑羽'
book.save('信息.xlsx')
print(sh['A1'].value)
print(sh.cell(2, 2).value)
import openpyxl
name2Age = {
'张飞' : 38,
'赵云' : 27,
'许褚' : 36,
'典韦' : 38,
'关羽' : 39,
'黄忠' : 49,
'徐晃' : 43,
'马超' : 23,
}
book = openpyxl.Workbook()
sh = book.active
sh.title = '年龄表'
sh['A1'] = '姓名'
sh['B1'] = '年龄'
row = 2
for name,age in name2Age.items():
sh.cell(row, 1).value = name
sh.cell(row, 2).value = age
row += 1
book.save('信息.xlsx')
import openpyxl
name2Age = [
['张飞' , 38 ] ,
['赵云' , 27 ] ,
['许褚' , 36 ] ,
['典韦' , 38 ] ,
['关羽' , 39 ] ,
['黄忠' , 49 ] ,
['徐晃' , 43 ] ,
['马超' , 23 ]
]
book = openpyxl.Workbook()
sh = book.active
sh.title = '年龄表'
sh['A1'] = '姓名'
sh['B1'] = '年龄'
for row in name2Age:
sh.append(row)
book.save('信息1.xlsx')
import openpyxl
wb = openpyxl.load_workbook('income.xlsx')
sheet = wb['2017']
sheet['A1'] = '修改一下'
sheet.insert_rows(2)
sheet.insert_rows(3,3)
sheet.insert_cols(2)
sheet.insert_cols(2,3)
sheet.delete_rows(2)
sheet.delete_rows(3,3)
sheet.delete_cols(2)
sheet.delete_cols(3,3)
wb.save('income-1.xlsx')
19.3文字 颜色、字体、大小修改
import openpyxl
from openpyxl.styles import Font,colors
wb = openpyxl.load_workbook('income.xlsx')
sheet = wb['2018']
sheet['A1'].font = Font(color="981818",
size=15,
bold=True,
italic=True
)
font = Font(color="981818")
for y in range(1, 100):
sheet.cell(row=3, column=y).font = font
font = Font(bold=True)
for x in range(1, 100):
sheet.cell(row=x, column=2).font = font
wb.save('income-1.xlsx')
import openpyxl
from openpyxl.styles import PatternFill
from openpyxl.drawing.image import Image
wb = openpyxl.load_workbook('income.xlsx')
sheet = wb['2018']
sheet['A1'].fill = PatternFill("solid", "E39191")
fill = PatternFill("solid", "E39191")
for y in range(1, 100):
sheet.cell(row=2, column=y).fill = fill
sheet.add_image(Image('2.jpg'), 'D1')
wb.save('income-1.xlsx')
19.4COM接口修改excel内容
第一步:安装 pip install pywin32
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
workbook = excel.Workbooks.Open(r"C:\Users\Administrator\PycharmProjects\days\income.xlsx")
sheet = workbook.Sheets('2017')
sheet.Cells(1,1).Value="你好"
workbook.Save()
workbook.Close()
excel.Quit()
sheet = None
book = None
excel.Quit()
excel = None
20.最大公约数和最小公倍数,x大于y就交换x和y的值,两个数中较的数开始做递减的循环
x = int(input('x = '))
y = int(input('y = '))
if x > y:
x, y = y, x
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print('%d和%d的最大公约数是%d' % (x, y, factor))
print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))
break
def gcd(x, y):
"""求最大公约数"""
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor
def lcm(x, y):
"""求最小公倍数"""
return x * y // gcd(x, y)
21.找出1~9999之间的所有完美数
import math
for num in range(1, 10000):
result = 0
for factor in range(1, int(math.sqrt(num)) + 1):
if num % factor == 0:
result += factor
if factor > 1 and num // factor != factor:
result += num // factor
if result == num:
print(num)
21.判断素数和回文数
for num in range(2, 100):
is_prime = True
for factor in range(2, int(math.sqrt(num)) + 1):
if num % factor == 0:
is_prime = False
break
if is_prime:
print(num, end=' ')
def is_prime(num):
"""判断一个数是不是素数"""
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
return False
return True if num != 1 else False
if __name__ == '__main__':
num = int(input('请输入正整数: '))
if is_palindrome(num) and is_prime(num):
print('%d是回文素数' % num)
22.输出斐波那契数列的前20个数,更新跑马灯
a = 0
b = 1
for _ in range(20):
a, b = b, a + b
print(a, end=' ')
def is_palindrome(num):
"""判断一个数是不是回文数"""
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
return total == num
import os
import time
def main():
content = '北京欢迎你为你开天辟地…………'
while True:
os.system('cls')
print(content)
time.sleep(0.2)
content = content[1:] + content[0]
if __name__ == '__main__':
main()
23.产生指定长度的验证码
import random
def generate_code(code_len=4):
"""
生成指定长度的验证码
:param code_len: 验证码的长度(默认4个字符)
:return: 由大小写英文字母和数字构成的随机验证码
"""
all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
last_pos = len(all_chars) - 1
code = ''
for _ in range(code_len):
index = random.randint(0, last_pos)
code += all_chars[index]
return code
24.设计一个函数返回给定文件名的后缀名
def get_suffix(filename, has_dot=False):
"""
获取文件名的后缀名
:param filename: 文件名
:param has_dot: 返回的后缀名是否需要带点
:return: 文件的后缀名
"""
pos = filename.rfind('.')
if 0 < pos < len(filename) - 1:
index = pos if has_dot else pos + 1
return filename[index:]
else:
return ''
25.设计一个函数返回传入的列表中最大和第二大的元素的值
def max2(x):
m1, m2 = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])
for index in range(2, len(x)):
if x[index] > m1:
m2 = m1
m1 = x[index]
elif x[index] > m2:
m2 = x[index]
return m1, m2
26.计算指定的年月日是这一年的第几天
def is_leap_year(year):
"""
判断指定的年份是不是闰年
:param year: 年份
:return: 闰年返回True平年返回False
"""
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year, month, date):
"""
计算传入的日期是这一年的第几天
:param year: 年
:param month: 月
:param date: 日
:return: 第几天
"""
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
][is_leap_year(year)]
total = 0
for index in range(month - 1):
total += days_of_month[index]
return total + date
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == '__main__':
main()
27.打印杨辉三角
def main():
num = int(input('Number of rows: '))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None] * (row + 1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
print(yh[row][col], end='\t')
print()
if __name__ == '__main__':
main()
28.双色球选号
from random import randrange, randint, sample
def display(balls):
"""
输出列表中的双色球号码
"""
for index, ball in enumerate(balls):
if index == len(balls) - 1:
print('|', end=' ')
print('%02d' % ball, end=' ')
print()
def random_select():
"""
随机选择一组号码
"""
red_balls = [x for x in range(1, 34)]
selected_balls = []
selected_balls = sample(red_balls, 6)
selected_balls.sort()
selected_balls.append(randint(1, 16))
return selected_balls
def main():
n = int(input('机选几注: '))
for _ in range(n):
display(random_select())
if __name__ == '__main__':
main()
29.定义类及使用类
class Student(object):
def __init__(self, name, age):
self.age = age
self.name = name
sex = "男"
def Study(self, course_name):
print(f"{self.age}岁的{self.name}正在学习{course_name}")
def watch(self):
if self.age < 18:
print("%s正在看熊出没" %(self.name))
else:
print("%s正在看岛国片" %(self.name))
xue = Student("小刚",5)
xue.watch()
xue.Study("英语")
29.1类的继承学习
class Person(object):
"""人"""
限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
def play(self):
print('%s正在愉快的玩耍.' % self._name)
def watch_av(self):
if self._age >= 18:
print('%s正在观看爱情动作片.' % self._name)
else:
print('%s只能观看《熊出没》.' % self._name)
class Student(Person):
"""学生"""
def __init__(self, name, age, grade):
super().__init__(name, age)
self._grade = grade
@property
def grade(self):
return self._grade
@grade.setter
def grade(self, grade):
self._grade = grade
def study(self, course):
print('%s的%s正在学习%s.' % (self._grade, self._name, course))
class Teacher(Person):
"""老师"""
def __init__(self, name, age, title):
super().__init__(name, age)
self._title = title
@property
def title(self):
return self._title
@title.setter
def title(self, title):
self._title = title
def teach(self, course):
print('%s%s正在讲%s.' % (self._name, self._title, course))
def main():
stu = Student('王大锤', 15, '初三')
stu.study('数学')
stu.watch_av()
t = Teacher('骆昊', 38, '砖家')
t.teach('Python程序设计')
t.watch_av()
if __name__ == '__main__':
main()
29.2抽象方法多态
Python从语法层面并没有像Java或C
from abc import ABCMeta, abstractmethod
class Pet(object, metaclass=ABCMeta):
"""宠物"""
def __init__(self, nickname):
self._nickname = nickname
@abstractmethod
def make_voice(self):
"""发出声音"""
pass
class Dog(Pet):
"""狗"""
def make_voice(self):
print('%s: 汪汪汪...' % self._nickname)
class Cat(Pet):
"""猫"""
def make_voice(self):
print('%s: 喵...喵...' % self._nickname)
def main():
pets = [Dog('旺财'), Cat('凯蒂'), Dog('大黄')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
29.3案例:奥特曼打小怪兽
from abc import ABCMeta, abstractmethod
from random import randint, randrange
class Fighter(object, metaclass=ABCMeta):
"""战斗者"""
__slots__ = ('_name', '_hp')
def __init__(self, name, hp):
"""初始化方法
:param name: 名字
:param hp: 生命值
"""
self._name = name
self._hp = hp
@property
def name(self):
return self._name
@property
def hp(self):
return self._hp
@hp.setter
def hp(self, hp):
self._hp = hp if hp >= 0 else 0
@property
def alive(self):
return self._hp > 0
@abstractmethod
def attack(self, other):
"""攻击
:param other: 被攻击的对象
"""
pass
class Ultraman(Fighter):
"""奥特曼"""
__slots__ = ('_name', '_hp', '_mp')
def __init__(self, name, hp, mp):
"""初始化方法
:param name: 名字
:param hp: 生命值
:param mp: 魔法值
"""
super().__init__(name, hp)
self._mp = mp
def attack(self, other):
other.hp -= randint(15, 25)
def huge_attack(self, other):
"""究极必杀技(打掉对方至少50点或四分之三的血)
:param other: 被攻击的对象
:return: 使用成功返回True否则返回False
"""
if self._mp >= 50:
self._mp -= 50
injury = other.hp * 3 // 4
injury = injury if injury >= 50 else 50
other.hp -= injury
return True
else:
self.attack(other)
return False
def magic_attack(self, others):
"""魔法攻击
:param others: 被攻击的群体
:return: 使用魔法成功返回True否则返回False
"""
if self._mp >= 20:
self._mp -= 20
for temp in others:
if temp.alive:
temp.hp -= randint(10, 15)
return True
else:
return False
def resume(self):
"""恢复魔法值"""
incr_point = randint(1, 10)
self._mp += incr_point
return incr_point
def __str__(self):
return '~~~%s奥特曼~~~\n' % self._name + \
'生命值: %d\n' % self._hp + \
'魔法值: %d\n' % self._mp
class Monster(Fighter):
"""小怪兽"""
__slots__ = ('_name', '_hp')
def attack(self, other):
other.hp -= randint(10, 20)
def __str__(self):
return '~~~%s小怪兽~~~\n' % self._name + \
'生命值: %d\n' % self._hp
def is_any_alive(monsters):
"""判断有没有小怪兽是活着的"""
for monster in monsters:
if monster.alive > 0:
return True
return False
def select_alive_one(monsters):
"""选中一只活着的小怪兽"""
monsters_len = len(monsters)
while True:
index = randrange(monsters_len)
monster = monsters[index]
if monster.alive > 0:
return monster
def display_info(ultraman, monsters):
"""显示奥特曼和小怪兽的信息"""
print(ultraman)
for monster in monsters:
print(monster, end='')
def main():
u = Ultraman('骆昊', 1000, 120)
m1 = Monster('狄仁杰', 250)
m2 = Monster('白元芳', 500)
m3 = Monster('王大锤', 750)
ms = [m1, m2, m3]
fight_round = 1
while u.alive and is_any_alive(ms):
print('========第%02d回合========' % fight_round)
m = select_alive_one(ms)
skill = randint(1, 10)
if skill <= 6:
print('%s使用普通攻击打了%s.' % (u.name, m.name))
u.attack(m)
print('%s的魔法值恢复了%d点.' % (u.name, u.resume()))
elif skill <= 9:
if u.magic_attack(ms):
print('%s使用了魔法攻击.' % u.name)
else:
print('%s使用魔法失败.' % u.name)
else:
if u.huge_attack(m):
print('%s使用究极必杀技虐了%s.' % (u.name, m.name))
else:
print('%s使用普通攻击打了%s.' % (u.name, m.name))
print('%s的魔法值恢复了%d点.' % (u.name, u.resume()))
if m.alive > 0:
print('%s回击了%s.' % (m.name, u.name))
m.attack(u)
display_info(u, ms)
fight_round += 1
print('\n========战斗结束!========\n')
if u.alive > 0:
print('%s奥特曼胜利!' % u.name)
else:
print('小怪兽胜利!')
if __name__ == '__main__':
main()
import random
class Card(object):
"""一张牌"""
def __init__(self, suite, face):
self._suite = suite
self._face = face
@property
def face(self):
return self._face
@property
def suite(self):
return self._suite
def __str__(self):
if self._face == 1:
face_str = 'A'
elif self._face == 11:
face_str = 'J'
elif self._face == 12:
face_str = 'Q'
elif self._face == 13:
face_str = 'K'
else:
face_str = str(self._face)
return '%s%s' % (self._suite, face_str)
def __repr__(self):
return self.__str__()
class Poker(object):
"""一副牌"""
def __init__(self):
self._cards = [Card(suite, face)
for suite in '????'
for face in range(1, 14)]
self._current = 0
@property
def cards(self):
return self._cards
def shuffle(self):
"""洗牌(随机乱序)"""
self._current = 0
random.shuffle(self._cards)
@property
def next(self):
"""发牌"""
card = self._cards[self._current]
self._current += 1
return card
@property
def has_next(self):
"""还有没有牌"""
return self._current < len(self._cards)
class Player(object):
"""玩家"""
def __init__(self, name):
self._name = name
self._cards_on_hand = []
@property
def name(self):
return self._name
@property
def cards_on_hand(self):
return self._cards_on_hand
def get(self, card):
"""摸牌"""
self._cards_on_hand.append(card)
def arrange(self, card_key):
"""玩家整理手上的牌"""
self._cards_on_hand.sort(key=card_key)
```python
def get_key(card):
return (card.suite, card.face)
def main():
p = Poker()
p.shuffle()
players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
for _ in range(13):
for player in players:
player.get(p.next)
for player in players:
print(player.name + ':', end=' ')
player.arrange(get_key)
print(player.cards_on_hand)
if __name__ == '__main__':
main()
29.4案例:工资结算系统
"""
某公司有三种类型的员工 分别是部门经理、程序员和销售员
需要设计一个工资结算系统 根据提供的员工信息来计算月薪
部门经理的月薪是每月固定15000元
程序员的月薪按本月工作时间计算 每小时150元
销售员的月薪是1200元的底薪加上销售额5%的提成
"""
from abc import ABCMeta, abstractmethod
class Employee(object, metaclass=ABCMeta):
"""员工"""
def __init__(self, name):
"""
初始化方法
:param name: 姓名
"""
self._name = name
@property
def name(self):
return self._name
@abstractmethod
def get_salary(self):
"""
获得月薪
:return: 月薪
"""
pass
class Manager(Employee):
"""部门经理"""
def get_salary(self):
return 15000.0
class Programmer(Employee):
"""程序员"""
def __init__(self, name, working_hour=0):
super().__init__(name)
self._working_hour = working_hour
@property
def working_hour(self):
return self._working_hour
@working_hour.setter
def working_hour(self, working_hour):
self._working_hour = working_hour if working_hour > 0 else 0
def get_salary(self):
return 150.0 * self._working_hour
class Salesman(Employee):
"""销售员"""
def __init__(self, name, sales=0):
super().__init__(name)
self._sales = sales
@property
def sales(self):
return self._sales
@sales.setter
def sales(self, sales):
self._sales = sales if sales > 0 else 0
def get_salary(self):
return 1200.0 + self._sales * 0.05
def main():
emps = [
Manager('刘备'), Programmer('诸葛亮'),
Manager('曹操'), Salesman('荀彧'),
Salesman('吕布'), Programmer('张辽'),
Programmer('赵云')
]
for emp in emps:
if isinstance(emp, Programmer):
emp.working_hour = int(input('请输入%s本月工作时间: ' % emp.name))
elif isinstance(emp, Salesman):
emp.sales = float(input('请输入%s本月销售额: ' % emp.name))
print('%s本月工资为: ¥%s元' %
(emp.name, emp.get_salary()))
if __name__ == '__main__':
main()
29.5案例:幸运的基督徒
"""
《幸运的基督徒》
有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。
"""
def main():
persons = [True] * 30
counter, index, number = 0, 0, 0
while counter < 15:
if persons[index]:
number += 1
if number == 9:
persons[index] = False
counter += 1
number = 0
index += 1
index %= 30
for person in persons:
print('基' if person else '非', end='')
if __name__ == '__main__':
main()
29.6案例:井子棋游戏
import os
def print_board(board):
print(board['TL'] + '|' + board['TM'] + '|' + board['TR'])
print('-+-+-')
print(board['ML'] + '|' + board['MM'] + '|' + board['MR'])
print('-+-+-')
print(board['BL'] + '|' + board['BM'] + '|' + board['BR'])
def main():
init_board = {
'TL': ' ', 'TM': ' ', 'TR': ' ',
'ML': ' ', 'MM': ' ', 'MR': ' ',
'BL': ' ', 'BM': ' ', 'BR': ' '
}
begin = True
while begin:
curr_board = init_board.copy()
begin = False
turn = 'x'
counter = 0
os.system('clear')
print_board(curr_board)
while counter < 9:
move = input('轮到%s走棋, 请输入位置: ' % turn)
if curr_board[move] == ' ':
counter += 1
curr_board[move] = turn
if turn == 'x':
turn = 'o'
else:
turn = 'x'
os.system('clear')
print_board(curr_board)
choice = input('再玩一局?(yes|no)')
begin = choice == 'yes'
if __name__ == '__main__':
main()
30.python的注释,计算1.01的365次方,input函数实现键盘输入
"""
这是Python的多行注释
"""
g_num
a,b = b,a
print(1.01**365)
a = input("请输入密码:")
print(a)
%s
%d
%f
%%
print("*",end="")
print("")
print("*",end="---")
print("*")
31.if else语句结构
age = 16
if age >=18:
print("你已经成年")
else:
print("你还没成年")
is_employee = True;
if not is_employee:
print("非本公司人员")
holiday_name = "生日"
if holiday_name == "情人节":
print("买玫瑰")
elif holiday_name == "平安夜":
print("吃苹果")
elif holiday_name == "生日":
print("买蛋糕")
else:
print("每天都是节日呀")
a = 16
holiday_name = "生日"
if holiday_name == "生日":
if a >=18:
print("买玫瑰")
else:
print("吃苹果")
32.while循环
i = 1
while i <=5:
print("hello,Python")
i = i + 1;
print("循环结束后的 i = %d" % i)
33.for循环判断
for num in [1,2,3]:
print(num)
if num == 2:
break
else:
print("你好")
34.生成随机数
import random
a = random.randint(12,20)
print(a)
35.定义函数和调用函数
def sum(num1,num2):
"""对两个数字求和"""
result = num1 + num2
print("%d + %d = %d" % (num1,num2,result))
if __name__ == '__main__':
sum(10,20)
def dayin():
print("-"*50)
"""
打印横线模块.py 是自己创建的文件
"""
import 打印横线模块
打印横线模块.dayin()
36.多值参数 *args 变量的函数,可以接收元组 **kwargs键值对参数,可以接收字典
def demo(num,*args,**kwargs):
print(num)
print(args)
print(kwargs)
if __name__ == '__main__':
demo(1,2,3,4,name="小明",age=18,gender=True)
def demo(num,*nums,**person):
print(num)
print(nums)
print(person)
if __name__ == '__main__':
demo(1,2,3,4,name="小明",age=18,gender=True)
37.函数递归,处理不确定的循环条件的时候格外有用
"""
计算1+2+3+.....+num
"""
def sum_numbers(num):
if num ==1:
return 1
temp = sum_numbers(num-1)
return num + temp
result = sum_numbers(100)
print(result)
38.numpy
38.1生成数组,设置指定的数据类型,输出0-10的数据,步长为2,调整数据类型
import numpy as np
import random
t1 = np.array([1,2,3,4])
print(t1,type(t1),t1.dtype)
t1 = np.array(range(1,4),dtype=float)
print(t1,t1.dtype)
t1 = np.array(range(1,4),dtype="float32")
print(t1,t1.dtype)
t1 = np.array([1,0,1,1,0],dtype=bool)
print(t1)
t1 = np.array(range(10))
print(t1)
t1 = np.arange(10)
print(t1)
t1 = np.arange(0,10,2)
print(t1)
t2 = t1.astype("int8")
print(t2,t2.dtype)
t1 = np.array([random.random() for i in range(3)])
print(t1,t1.dtype)
t1 = np.round(t1,2)
print(t1,t1.dtype)
38.2一二三维数组,更改数组形状,在不知道t5元素个数的情况下,将其变成1维数组,数组的计算函数
import numpy as np
t1 = np.arange(12)
print(t1)
print(t1.shape)
t2 = np.array([[1,2,3],[4,5,6]])
print(t2)
"""
#输出:
[[1 2 3]
[4 5 6]]
"""
print(t2.shape)
t3 = np.array([[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]])
print(t3)
"""
#输出:
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]]
"""
print(t3.shape)
t4 = t1.reshape((3,4))
print(t4)
print(t4.shape)
"""
#输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
"""
t5 = t1.reshape((2,2,3))
print(t5)
"""
#输出:
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
"""
t6 = t5.reshape((6,2))
print(t6)
"""
#输出:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]]
"""
t7 = t5.reshape(12)
print(t7)
t8 = t5.flatten()
print(t8)
print(t5+2)
"""
#输出:
[[[ 2 3 4]
[ 5 6 7]]
[[ 8 9 10]
[11 12 13]]]
"""
t6 = np.arange(0,3)
print(t5-t6)
"""
#输出:
[[[0 0 0]
[3 3 3]]
[[6 6 6]
[9 9 9]]]
"""
import numpy as np
"""
常用的计算函数:
求和:t.sum(axis=None) axis参数可以是:0,1,2
均值:t.mean(a,axis=None) 受离群点的影响较大
中值:np.median(t,axis=None)
最大值:t.max(axis=None)
最小值:t.min(axis=None)
极值:np.ptp(t,axis=None) 最大值和最小值只差
标准差:t.std(axis=None)
"""
t1 = np.arange(0,12).reshape(3,4)
print(t1)
"""
#输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
"""
t2 = np.sum(t1)
print(t2)
print(np.sum(t1,axis=0))
print(np.sum(t1,axis=1))
print(np.mean(t1))
print(np.mean(t1,axis=0))
print(np.mean(t1,axis=1))
print(np.median(t1))
print(np.median(t1,axis=0))
print(np.median(t1,axis=1))
print(np.max(t1))
print(np.max(t1,axis=0))
print(np.max(t1,axis=1))
print(np.min(t1))
print(np.min(t1,axis=0))
print(np.min(t1,axis=1))
print(np.ptp(t1))
print(np.ptp(t1,axis=0))
print(np.ptp(t1,axis=1))
38.3读取csv文件,进行转置方法
import numpy as np
"""
sj.csv:CSV文件路劲
delimiter:CSV文件数据中间都是通过","逗号来分割的,所以就填写数据分割的符号
dtype:加载的数据以什么类型显示,正常情况不设置的话是float类型,数据以科学计数法显示,改成int可以正常显示
unpack:是否转置,True表示要转置,False表示不进行转置显示
还有几个没有展示的参数:
frame:可以是.gz或bz2压缩文件
skiprows:跳过前x行,一般跳过第一行表头
usecols: 读取指定的列,索引,元祖类型
"""
t1 = np.loadtxt("sj.csv",delimiter =",",dtype="int",unpack=False)
print(t1)
"""
#输出:
[[ 12 78 45]
[450 784 451]
[412 3 7]]
"""
print(t1.transpose())
"""
#输出:
[[ 12 450 412]
[ 78 784 3]
[ 45 451 7]]
"""
print(t1.T)
"""
#输出:
[[ 12 450 412]
[ 78 784 3]
[ 45 451 7]]
"""
print(t1.swapaxes(1,0))
"""
#输出:
[[ 12 450 412]
[ 78 784 3]
[ 45 451 7]]
"""
38.4读取csv文件取不连续的行,列
CSV内容如下:
[[ 12 78 45]
[450 784 451]
[412 3 7]]
"""
#取行
#取第3行
print(t1[2]) #输出:[412 3 7]
#连续取多行,从第2行开始往后的所有行数都取
print(t1[1:])
"""
输出:
[[450 784 451]
[412 3 7]]
"""
#取不连续的行,第1行和第3行,注意是:[[]]
print(t1[[0,2]])
"""
输出:
[[ 12 78 45]
[412 3 7]]
"""
#取列
#取第一列
print(t1[:,0]) #输出:[ 12 450 412]
#取连续的多列,取第2列往后的所有列
print(t1[:,1:])
"""
输出:
[[ 78 45]
[784 451]
[ 3 7]]
"""
#取不连续的多列,取第1列和第3列
print(t1[:,[0,2]])
"""
[[ 12 45]
[450 451]
[412 7]]
"""
#取行和列交叉的值,取第2行和第3列交叉的值
print(t1[1,2]) #输出:451
#取多行和多列交叉的值,行值:0:2,列值:0:3
print(t1[0:2,0:3])
"""
[[ 12 78 45]
[450 784 451]]
"""
print(t1[[0,2],[0,1]])
print(t1[[0,2,1],[0,1,0]])
38.5下面的方式对numpy设置值
import numpy as np
t1 = np.arange(0,24).reshape(4,6)
print(t1)
"""
#输出:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
"""
t1[t1<10] = 0
print(t1)
"""
#输出:
[[ 0 0 0 0 0 0]
[ 0 0 0 0 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
"""
t2 = np.where(t1<10,2,10)
print(t2)
"""
#输出:
[[ 2 2 2 2 2 2]
[ 2 2 2 2 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]]
"""
t3 = t1.clip(10,20)
print(t3)
"""
#输出:
[[10 10 10 10 10 10]
[10 10 10 10 10 11]
[12 13 14 15 16 17]
[18 19 20 20 20 20]]
"""
38.6数组的拼接
import numpy as np
t1 = np.arange(0,12).reshape(2,6)
print(t1)
"""
#输出:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
"""
t2 = np.arange(12,24).reshape(2,6)
print(t2)
"""
#输出:
[[12 13 14 15 16 17]
[18 19 20 21 22 23]]
"""
t3 = np.vstack((t1,t2))
print(t3)
"""
#输出:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
"""
t4 = np.hstack((t1,t2))
print(t4)
"""
#输出:
[[ 0 1 2 3 4 5 12 13 14 15 16 17]
[ 6 7 8 9 10 11 18 19 20 21 22 23]]
"""
38.7数组的行列交换
import numpy as np
t1 = np.arange(0,12).reshape(2,6)
print(t1)
"""
#输出:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
"""
t1[[0,1],:]= t1[[1,0],:]
print(t1)
"""
#输出:
[[ 6 7 8 9 10 11]
[ 0 1 2 3 4 5]]
"""
t1[:,[3,5]] = t1[:,[5,3]]
print(t1)
"""
#输出结果:
[[ 0 1 2 5 4 3]
[ 6 7 8 11 10 9]]
"""
38.8两个表格合并拼接案例
import numpy as np
path1 = "数据1.csv"
path2 = "数据2.csv"
t1 = np.loadtxt(path1,delimiter =",",dtype="str",unpack=False)
t2 = np.loadtxt(path2,delimiter =",",dtype="str",unpack=False,skiprows=1)
t2[:,[0,3]] = t2[:,[3,0]]
t2[:,[1,2]] = t2[:,[2,1]]
zero_datas = np.zeros((t1.shape[0],1))
t1 = np.hstack((t1,zero_datas))
one_datas = np.ones((t2.shape[0],1))
t2 = np.hstack((t2,one_datas))
t3 = np.vstack((t1,t2))
print(t3)
"""
#输出:
[['序号' '姓名' '年龄' '性别' '0.0']
['1' '王一' '11' '男' '0.0']
['2' '李二' '13' '女' '0.0']
['3' '胡三' '14' '女' '0.0']
['4' '牛四' '43' '男' '0.0']
['1' '牛牛' '69' '女' '1.0']
['2' '妞妞' '78' '男' '1.0']
['3' '哈哈' '88' '女' '1.0']
['4' '龟龟' '96' '男' '1.0']]
"""
38.9输出特殊数组
import numpy as np
t1 = np.zeros((2,3))
print(t1)
"""
#输出:
[[0. 0. 0.]
[0. 0. 0.]]
"""
t2 = np.ones((2,3))
print(t2)
"""
#输出:
[[1. 1. 1.]
[1. 1. 1.]]
"""
t3 = np.eye(5)
print(t3)
"""
#输出:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
"""
t3[t3==1] = -1
print(t3)
"""
#输出:
[[-1. 0. 0. 0. 0.]
[ 0. -1. 0. 0. 0.]
[ 0. 0. -1. 0. 0.]
[ 0. 0. 0. -1. 0.]
[ 0. 0. 0. 0. -1.]]
"""
t1 = np.arange(0,24).reshape(4,6)
print(t1)
"""
#输出:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
"""
t2 = np.argmax(t1,axis=0)
print(t2)
t3 = np.argmin(t1,axis=1)
print(t3)
38.10numpy生成随机数
import numpy as np
t1 = np.random.randint(10,20,(4,5))
print(t1)
"""
#输出:
[[19 19 18 18 11]
[12 10 12 13 14]
[18 14 12 17 19]
[16 16 18 16 13]]
"""
np.random.seed(10)
t1 = np.random.randint(10,20,(4,5))
print(t1)
38.11生成均匀分布,生成正太分布
import numpy as np
t1 = np.random.rand(2,3)
print(t1)
"""
#输出:
[[0.04274737 0.1361201 0.84016315]
[0.44552229 0.7172352 0.27860468]]
"""
t1 = np.random.rand(2,3,4)
print(t1)
"""
#输出:
[[[0.24767532 0.16923183 0.62929336 0.33167291]
[0.2348981 0.01604486 0.80277711 0.28230471]
[0.23967977 0.08896188 0.56858435 0.76727779]]
[[0.47388122 0.12789331 0.39452345 0.70882385]
[0.03865579 0.22865491 0.61875551 0.54528252]
[0.62982165 0.8362343 0.55457358 0.09833485]]]
"""
t1 = np.random.uniform(0,10,(3,4))
print(t1)
"""
#输出:
[[3.99960109 0.56396094 4.1519833 4.36621776]
[0.34286939 6.2153802 4.62656694 8.63443251]
[9.86762737 5.19151595 6.27414267 7.93814561]]
"""
t1 = np.random.randn(2,3)
print(t1)
"""
#输出:
[[ 0.6605607 0.30783449 -1.46573396]
[-0.98326193 1.52080767 0.10181919]]
"""
t1 = np.random.randn(2,2,3)
print(t1)
"""
#输出:
[[[ 2.37741191 1.87040913 0.45063207]
[ 0.56533405 0.00433109 -1.08064214]]
[[ 1.33627413 -0.22782971 -1.36614693]
[ 0.9860127 0.60480094 -2.43832716]]]
"""
"""
normal(loc,scale,(size))
loc:分布中心是loc,概率分布的均值 这里给的是:1
scale:标准差 这里给的是:2
size:形状 这里给的是(3,4)
"""
t1 = np.random.normal(1,2,(3,4))
print(t1)
"""
#输出:
[[ 1.55218173 5.54394444 1.66259268 2.05608633]
[ 0.50338512 3.74396925 -1.19796599 -3.01734329]
[-0.70629025 2.79923655 4.09952597 1.39394705]]
"""
38.12统计数据是nan的数据个数,统计数据非0的数据个数,将数据是nan的替换为0
import numpy as np
"""
nan(不是一个数)和inf(无穷大),数据类型都是浮点数类型float
"""
t1 = np.arange(0,12).astype(float).reshape(3,4)
t1[[0,2]] = np.nan
print(t1)
"""
#输出:
[[nan nan nan nan]
[ 4. 5. 6. 7.]
[nan nan nan nan]]
"""
print(t1!=t1)
"""
#输出:
[[ True True True True]
[False False False False]
[ True True True True]]
"""
print(np.count_nonzero(np.isnan(t1)))
t2 = np.count_nonzero(t1!=t1)
print(t2)
print(np.count_nonzero(t1))
t1[np.isnan(t1)] = 0
print(t1)
"""
#输出:
[[0. 0. 0. 0.]
[4. 5. 6. 7.]
[0. 0. 0. 0.]]
"""
38.13将有nan的数据通过均值进行填充
import numpy as np
t1 = np.arange(0,12).reshape(3,4).astype("float")
print(t1)
"""
#输出:
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]]
"""
t1[[1,1],[2,3]] = np.nan
print(t1)
"""
#输出:
[[ 0. 1. 2. 3.]
[ 4. 5. nan nan]
[ 8. 9. 10. 11.]]
"""
for i in range(t1.shape[1]):
temp_col = t1[:,i]
nan_num = np.count_nonzero(temp_col!=temp_col)
if nan_num!=0:
temp_not_nan_col = temp_col[temp_col==temp_col]
temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()
print(t1)
"""
#输出:
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]]
"""
39.pandas
39.1list,numpy.array,pandas.DataFrame,numpy:,pandas:
[[1,2],[3,4]]
[[1 2]
[3 4]]
39.2安装anaconda
一.安装anaconda 下载网址:https://www.anaconda.com/products/individual#Downloads
39.3安装第三方包
二.安装如下第三方包
pip install -i https://pypi.doubanio.com/simple pandas
pip install -i https://pypi.doubanio.com/simple jupyter
pip install -i https://pypi.doubanio.com/simple xlrd
pip install -i https://pypi.doubanio.com/simple openpyxl
pip install -i https://pypi.doubanio.com/simple matplotlib
pip install -i https://pypi.doubanio.com/simple pillow
39.4创建一个Series和切片,获取一个不存在的值让其返回一个默认值,获取b的值,将其修改成22,掩码取值,取值大于2的值,或者使用:s[s>2]
import pandas as pd
s = pd.Series([1,2,3])
print(s)
0 1
1 2
2 3
dtype: int64
s = pd.Series([1,2,3],
index=list("abc"),
dtype="int64",
name="num"
)
print(s)
a 1
b 2
c 3
Name: num, dtype: int64
d = {"a" :1,"b":2,"c":3}
s = pd.Series(d)
print(s)
"""
#输出:
a 1
b 2
c 3
dtype: int64
"""
print(s[0:2])
"""
#输出:
a 1
b 2
dtype: int64
"""
print(s[::-1])
"""
#输出:
c 3
b 2
a 1
dtype: int64
"""
print(s[::2])
"""
#输出:
a 1
c 3
dtype: int64
"""
print(s.get("d",888))
print(s.get("a"))
s["b"] = 22
print(s)
"""
#输出:
a 1
b 22
c 3
dtype: int64
"""
mask = s >2
print(mask)
"""
#输出:
a False
b False
c True
dtype: bool
"""
print(s[s>2])
"""
#输出:
c 3
dtype: int64
"""
s[1] = 33
print(s)
"""
#输出:
a 1
b 33
c 3
dtype: int64
"""
s[[True,False,True]] = [11,23]
print(s)
"""
#输出:
a 11
b 2
c 23
dtype: int64
"""
s = pd.Series(3.0,index=["a","b"])
print(s)
a 3.0
b 3.0
dtype: float64
39.5创建一个DataFrame
import pandas as pd
list_2d = [[1,2],
[3,4]]
df = pd.DataFrame(list_2d)
print(df)
0 1
0 1 2
1 3 4
list_2d = [[1,2],
[3,4]]
df = pd.DataFrame(list_2d,columns=["A","B"],index=["x","y"])
print(df)
A B
x 1 2
y 3 4
d = {"A":[1,3],"B":[2,4]}
df = pd.DataFrame(d,index=["x","y"])
print(df)
A B
x 1 2
y 3 4
39.6pandas读取第一个表格的内容
import pandas as pd
"""
squeeze=False(默认) 表明是DataFrame结构
squeeze=True 表明是Series结构
mangle_dupe_cols=True(默认) 是否重命名重复列
nrows=5,要解析5行内容,完整图标只显示头5行内容,默认是None,显示全部
thousands=None(默认)
thousands="," 将文本类型千分位上的逗号去掉,变成数字类型 如:2,123 ->2123
convert_float=True(默认) 将浮点数转换成int类型 例:1.0 -> 1
"""
df = pd.read_excel("123.xlsx")
print(df)
df = pd.read_excel("123.xlsx",sheet_name="2月")
print(df)
df = pd.read_excel("123.xlsx",sheet_name=2)
print(df)
df = pd.read_excel("123.xlsx",sheet_name=[1,"3月"])
print(df)
print(df[1])
print(df["3月"])
df = pd.read_excel("123.xlsx",sheet_name=None)
print(df)
print(df["3月"])
df = pd.read_excel("123.xlsx",sheet_name=0,header=None)
print(df)
0 1 2
0 月份 销量 销售额
1 1月份 100 1000
import pandas as pd
df = pd.read_excel("123.xlsx",sheet_name=0,header=1)
print(df)
1月份 100 1000
0 1月份 101 1050
df = pd.read_excel("123.xlsx",sheet_name=0,header=[0,1])
print(df)
月份 销量 销售额
1月份 100 1000
0 1月份 101 1050
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=5,header=[0,1])
print(df)
"""
#输出:
京东 淘宝 拼多多
销量 利润 销量 利润 销量 利润
0 221 569 587 75 78 94
1 236 785 964 415 96 26
2 245 5789 56 97 47 17
"""
print(df[("京东","利润")]+df[("淘宝","利润")]+df[("拼多多","利润")])
"""
569+75+94=738
#输出:
0 738
1 1226
2 5903
dtype: int64
"""
print(df["京东"]+df["淘宝"]+df["拼多多"])
"""
#输出:
销量 利润
0 886 738
1 1296 1226
2 348 5903
"""
df_total = df["京东"]+df["淘宝"]+df["拼多多"]
df_total.columns = pd.MultiIndex.from_product(
[ ["总量"],
df_total.columns]
)
df1 = df.join(df_total)
print(df1)
"""
#输出:
京东 淘宝 拼多多 总量
销量 利润 销量 利润 销量 利润 销量 利润
0 221 569 587 75 78 94 886 738
1 236 785 964 415 96 26 1296 1226
2 245 5789 56 97 47 17 348 5903
"""
df = pd.read_excel("123.xlsx",sheet_name=0,header=None,index_col=2)
print(df)
2 0 1
销售额 月份 销量
1000 1月份 100
1050 1月份 101
df = pd.read_excel("123.xlsx",sheet_name=0,header=None,usecols="A,C")
print(df)
0 2
0 月份 销售额
1 1月份 1000
2 1月份 1050
df = pd.read_excel("123.xlsx",sheet_name=0,header=None,usecols="A,B:C")
print(df)
0 1 2
0 月份 销量 销售额
1 1月份 100 1000
2 1月份 101 1050
print(df.index)
RangeIndex(start=0, stop=3, step=1)
df = pd.read_excel("123.xlsx",sheet_name=0,header=None,usecols=[0,2])
print(df)
0 2
0 月份 销售额
1 1月份 1000
2 1月份 1050
df = pd.read_excel("123.xlsx",usecols=["月份","销量"])
print(df)
月份 销量
0 1月份 100
1 1月份 101
df = pd.read_excel("123.xlsx",sheet_name="1月",header=None,skiprows=1)
print(df)
0 1 2
0 1月份 100 1000
1 1月份 101 1050
df = pd.read_excel("123.xlsx",sheet_name="1月",header=None,skiprows=[1,2])
print(df)
0 1 2
0 月份 销量 销售额
39.7添加列标题,查看每列的数据类型,
df = pd.read_excel("234.xlsx",header=None,names=["月份","销量","销售额"])
print(df)
月份 销量 销售额
0 1 245 789
1 2 759 452
2 3 452 741
print(df.dtypes)
月份 int64
销量 int64
销售额 int64
dtype: object
).convert_dtypes()
df = pd.read_excel("234.xlsx",header=None,names=["月份","销量","销售额"],
dtype={"月份":"str","销量":"string"})
df["月份"] = df["月份"].astype("string")
print(df.dtypes)
月份 string
销量 string
销售额 int64
dtype: object
df["销售额"] = df["销售额"].astype(str).astype("string")
print(df.select_dtypes(include="string"))
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=1)
print(df)
"""
#输出:
日期 日期1 日期2 日期3 日期4
0 20210522 2021-05-22 22/05/2021 2021-05-22 2021-05-22 23:26:10
"""
print(df.dtypes)
"""
#输出:
日期 int64
日期1 datetime64[ns]
日期2 object
日期3 object
日期4 object
dtype: object
"""
df = pd.read_excel("234.xlsx",sheet_name=1,parse_dates=[0,1,2,3,4])
print(df.dtypes)
"""
#输出:
日期 datetime64[ns]
日期1 datetime64[ns]
日期2 datetime64[ns]
日期3 datetime64[ns]
日期4 object
dtype: object
"""
df = pd.read_excel("234.xlsx",sheet_name=1,parse_dates=[[0,1]])
print(df)
"""
#输出:
日期_日期1 日期2 日期3 日期4
0 2021-05-22 00:00:00-22:00 22/05/2021 2021-05-22 2021-05-22 23:26:10
"""
df = pd.read_excel("234.xlsx",sheet_name=1,parse_dates={"年_月_日":[0,1]})
print(df)
"""
#输出:
年_月_日 日期2 日期3 日期4
0 2021-05-22 00:00:00-22:00 22/05/2021 2021-05-22 2021-05-22 23:26:10
"""
39.8object类型日期转换成日期格式
import pandas as pd
读取文件的时候加上如下参数即可:parse_dates=[0]表示是第0列的数据
parse_dates=[0],date_parser=lambda x: pd.to_datetime(x,format="%Y年%m月%d日")
df = pd.read_excel("234.xlsx",sheet_name=1,parse_dates=[0],date_parser=lambda x: pd.to_datetime(x,format="%Y年%m月%d日"))
print(df)
"""
#输出:
日期 日期1 日期2 日期3 日期4
0 2021-05-23 2021-05-22 22/05/2021 2021-05-22 2021-05-22 23:26:10
"""
39.9替换nan值的方法
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=2)
print(df)
"""
#输出:
列1 列2
0 a 0
1 NaN NaN
2 NaN
3 b 1
"""
df = pd.read_excel("234.xlsx",sheet_name=2,na_values=["a",0," "])
print(df)
"""
#输出:
列1 列2
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 b 1.0
"""
df = pd.read_excel("234.xlsx",sheet_name=2,na_values={"列2":["a",0," "]})
print(df)
"""
#输出:
列1 列2
0 a NaN
1 NaN NaN
2 NaN NaN
3 b 1.0
"""
39.10将数据第1列都加上10,第2列乘以2倍,通过索引获取列的值和更改列的值,显示b列值大于11的值,修改a列和b列值
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=2)
print(df)
"""
#输出:
a b
0 1 10
1 2 20
"""
"a":lambda x:x.strip(),
df = pd.read_excel("234.xlsx",sheet_name=2,
converters={
"a":lambda x:x+10,
"b":lambda x:x*2,
})
print(df)
"""
#输出:
a b
0 11 20
1 12 40
"""
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=2)
print(df)
"""
#输出:
a b
0 1 10
1 2 20
"""
print(df["b"]>11)
"""
#输出:
0 False
1 True
Name: b, dtype: bool
"""
print(df[df["b"]>11])
"""
#输出:
a b
1 2 20
"""
print(df[["b"]])
"""
#输出:
b
0 10
1 20
"""
print(df[[True,False]])
"""
#输出:
a b
0 1 10
"""
df["b"] = [101,201]
print(df)
"""
#输出:
a b
0 1 101
1 2 201
"""
df[["a","b"]] = [[101,201],[202,203]]
print(df)
"""
#输出:
a b
0 101 201
1 202 203
"""
39.11pandas写excel文件
import pandas as pd
"""
"""
df = pd.DataFrame(
{
"销量":[10,20],
"售价":[100,200],
}
)
print(df)
"""
#输出:
销量 售价
0 10 100
1 20 200
"""
df.to_excel("tb.xlsx")
"""
index=True(默认) 输出行标签 如:index=False 不输出行标签
sheet_name 输出的表格sheet名称
float_format=None(默认) 浮点数输出格式,float_format="%.2f",有小数的保留两位小数
na_rep="" 缺省值输出的表现形式,可以将空白的缺省值填充为任何字符串,如:na_rep="我是空值"
"""
df.to_excel("tb1.xlsx",index=False,sheet_name="你好",float_format="%.2f",na_rep="")
import pandas as pd
df = pd.DataFrame(
{
"销量":[10,20],
"售价":[100,200],
},
index=["aaa","bbb"]
)
print(df)
"""
#输出:
销量 售价
aaa 10 100
bbb 20 200
"""
df.index.name = "货号"
print(df)
"""
#输出:
货号 销量 售价
aaa 10 100
bbb 20 200
"""
df.to_excel("tb.xlsx")
39.12ExcelWriter类
import pandas as pd
from datetime import datetime
df1 = pd.DataFrame(
{
"日期":[datetime(2021,5,23),datetime(2021,5,24)],
"销量":[10,100]
}
)
df2 = pd.DataFrame(
{
"日期":[datetime(2021,6,23),datetime(2021,6,24)],
"销量":[20,200]
}
)
with pd.ExcelWriter("tabao.xlsx",datetime_format="YYYY-MM-DD") as writer:
df1.to_excel(writer,sheet_name="AAA")
df2.to_excel(writer,sheet_name="BBB")
39.13读写csv文件
import pandas as pd
df = pd.DataFrame({
"售价":[25,37],
"销量":[100,199]
})
"""
sep:以|进行分隔,一般是以逗号分隔
encoding="GBK" 编码方式是gbk,如果要读的话编码方式必须和写的是一样才不出错,还有utf8格式
"""
df.to_csv("cs.csv",index=False,encoding="GBK",sep="|")
df = pd.read_csv("cs.csv",encoding="GBK")
print(df)
"""
#输出:
售价|销量
0 25|100
1 37|199
"""
39.14pandas数据切片
import pandas as pd
df = pd.DataFrame({
"A":[1,4,7],
"B":[2,5,8],
"C":[3,6,9]
},index=["x","y","z"])
print(df)
"""
#输出:
A B C
x 1 2 3
y 4 5 6
z 7 8 9
"""
print(df[0:2])
"""
#输出:
A B C
x 1 2 3
y 4 5 6
"""
print(df["x":"z"])
"""
#输出:
A B C
x 1 2 3
y 4 5 6
z 7 8 9
"""
39.14.1df.loc方法选择数据
import pandas as pd
df = pd.DataFrame({
"A":[1,4,7],
"B":[2,5,8],
"C":[3,6,9]
},index=["x","y","z"])
print(df)
"""
#输出:
A B C
x 1 2 3
y 4 5 6
z 7 8 9
"""
print(df.loc["x"])
"""
#输出:
A 1
B 2
C 3
"""
print(df.loc["x","B"])
print(df.loc[["x","y"],["B","C"]])
"""
#输出:
B C
x 2 3
y 5 6
"""
print(df.loc[[True,True,False],[False,True,False]])
"""
#输出:
B
x 2
y 5
"""
print(df.loc["x":"y","A":"B"])
"""
#输出:
A B
x 1 2
y 4 5
"""
print(df.loc[:,"B":"C"])
"""
#输出:
B C
x 2 3
y 5 6
z 8 9
"""
print(df.loc["x":"y",:])
"""
#输出:
A B C
x 1 2 3
y 4 5 6
"""
print(df.loc[:,::-1])
"""
#输出:
C B A
x 3 2 1
y 6 5 4
z 9 8 7
"""
print(df.loc[::-1,:])
"""
#输出:
A B C
z 7 8 9
y 4 5 6
x 1 2 3
"""
print(df.loc[::2,::2])
"""
#输出:
A C
x 1 3
z 7 9
"""
39.14.2df.iloc方法的使用选择数据
import pandas as pd
df = pd.DataFrame({
"A":[1,4,7],
"B":[2,5,8],
"C":[3,6,9]
},index=list("xyz"))
print(df)
"""
#输出:
A B C
x 1 2 3
y 4 5 6
z 7 8 9
"""
print(df.iloc[0])
"""
#输出:
A 1
B 2
C 3
Name: x, dtype: int64
"""
print(df.iloc[[0,1],[1,2]])
"""
#输出:
B C
x 2 3
y 5 6
"""
print(df.iloc[[True,False,True],[True,False,True]])
"""
#输出:
A C
x 1 3
z 7 9
"""
print(df.iloc[0:2,1:3])
"""
#输出:
B C
x 2 3
y 5 6
"""
39.15pandas数据统计,数据透视表制作
import pandas as pd
df = pd.read_excel("234.xlsx",sheet_name=4)
print(df)
"""
#输出:
花费 时间 星期
0 13.6 中午 星期一
1 56.3 下午 星期二
2 14.8 中午 星期一
3 63.1 下午 星期三
4 69.3 下午 星期四
"""
df1 = df.groupby(["时间","星期"]).sum()
print(df1)
"""
#输出:
时间 星期 花费
下午 星期三 63.1
星期二 56.3
星期四 69.3
中午 星期一 28.4
"""
df1 = df.groupby(["时间","星期"]).sum().loc[lambda df:df["花费"]>50]
print(df1)
"""
#输出:
时间 星期 花费
下午 星期三 63.1
星期二 56.3
星期四 69.3
"""
import pandas as pd
import numpy as np
data = pd.read_excel("income_da.xlsx",sheet_name=2)
print(data)
"""
#输出:
季度 产业 生产总值
0 第一季度 第一产业 313202
1 第二季度 第一产业 788378
2 第三季度 第一产业 880697
3 第四季度 第一产业 940888
4 第一季度 第二产业 922362
5 第二季度 第二产业 739885
6 第三季度 第二产业 659360
7 第四季度 第二产业 492945
8 第一季度 第三产业 101466
9 第二季度 第三产业 629950
10 第三季度 第三产业 901960
11 第四季度 第三产业 144799
12 第一季度 第四产业 616544
13 第二季度 第四产业 944618
14 第三季度 第四产业 805532
15 第四季度 第四产业 494275
"""
print(data.index)
print(data.index.values)
data_1 = pd.pivot_table(data=data,index="季度",columns="产业",values="生产总值",aggfunc=np.sum)
print(data_1)
"""
#输出:
产业 第一产业 第三产业 第二产业 第四产业
季度
第一季度 313202 101466 922362 616544
第三季度 880697 901960 659360 805532
第二季度 788378 629950 739885 944618
第四季度 940888 144799 492945 494275
"""
print(data_1.index)
print(data_1.index.values)
data_2 = pd.crosstab(data["季度"],data["产业"],values=data["生产总值"],aggfunc=np.sum,normalize="index")
print(data_2)
"""
#输出:
产业 第一产业 第三产业 第二产业 第四产业
季度
第一季度 0.160323 0.051939 0.472141 0.315598
第三季度 0.271188 0.277736 0.203033 0.248043
第二季度 0.254083 0.203024 0.238455 0.304437
第四季度 0.453898 0.069853 0.237804 0.238445
"""
39.16将数组数据转换成DataFrame数据结构中
import pandas as pd
data = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
df = pd.DataFrame(
data,
columns=list("ABCD"),
index=list("axyz")
)
print(df)
"""
#输出:
A B C D
a 1 2 3 4
x 5 6 7 8
y 9 10 11 12
z 13 14 15 16
"""
df["A"] = 100
df["B"]= df["B"]*10
df["E"] = df["C"]+df["D"]
print(df)
"""
#输出:
A B C D E
a 100 20 3 4 7
x 100 60 7 8 15
y 100 100 11 12 23
z 100 140 15 16 31
"""
print(df.loc[df["E"]>15,"E"])
"""
#输出:
y 23
z 31
Name: E, dtype: int64
"""
39.17pandas对于加减乘除运算遇到分母为0或者单元格为空值的处理方法
import pandas as pd
import numpy as np
pd.options.mode.use_inf_as_na = True
df = pd.DataFrame(
[[1,2],
[1,np.NaN],
[np.NaN,1]],
columns=list("AB")
)
print(df)
"""
#输出:
A B
0 1.0 2.0
1 1.0 NaN
2 NaN 1.0
"""
"""
加法:df["A"].add(df["B"],fill_value=0)
减法:df["A"].sub(df["B"],fill_value=0)
陈法:df["A"].mul(df["B"],fill_value=0)
除法:df["A"].div(df["B"],fill_value=0)
"""
print(df["A"].add(df["B"],fill_value=0))
"""
#输出:
0 3.0
1 1.0
2 1.0
dtype: float64
"""
print(df["A"].div(df["B"],fill_value=0))
"""
#输出:
0 0.5
1 NaN
2 0.0
dtype: float64
"""
40.python-docx
安装:pip install python-docx
import docx
from docx.enum.text import WD_BREAK
from docx.shared import RGBColor, Pt
from docx.oxml.ns import qn
doc = docx.Document("test.docx")
print(dir(doc))
print(doc.paragraphs)
"""
#输出:
[<docx.text.paragraph.Paragraph object at 0x0000000002D86670>,
<docx.text.paragraph.Paragraph object at 0x0000000002D86880>,
<docx.text.paragraph.Paragraph object at 0x0000000002D868E0>,
<docx.text.paragraph.Paragraph object at 0x0000000002D86A90>,
<docx.text.paragraph.Paragraph object at 0x0000000002D86970>]
"""
print(len(doc.paragraphs))
print(doc.paragraphs[0].text)
print(len(doc.paragraphs[0].runs))
print(doc.paragraphs[0].runs[0].text)
"""
WD_BREAK.LINE: 这一段后面,换行符 ,空出一行
WD_BREAK.PAGE: 这一段后面,直接增加一个换页符,进行换页
WD_BREAK.COLUMN: 这一段后面进行换页,并且在下一页还空出一行
WD_BREAK.LINE_CLEAR_LEFT:
WD_BREAK.LINE_CLEAR_RIGHT:
WD_BREAK.LINE_CLEAR_ALL:
"""
doc.paragraphs[0].runs[0].add_break(break_type=WD_BREAK.LINE)
"""
font:
bold:字体加粗
all_caps:字母大写
color:字体颜色
complex_script:复杂脚本
double_strike:双删除线
emboss:浮雕
hidden:隐藏
italic:斜体
outline:外框
size:字体大小
underline:下划线
clear():清除内容
"""
doc.paragraphs[0].runs[0].font.bold = True
doc.paragraphs[0].runs[0].font.all_caps = True
doc.paragraphs[0].runs[0].clear()
doc.paragraphs[0].runs[0].font.color.rgb =RGBColor(0,205,205)
doc.paragraphs[0].runs[0].font.complex_script = True
doc.paragraphs[0].runs[0].font.double_strike = True
doc.paragraphs[0].runs[0].font.emboss = True
doc.paragraphs[0].runs[0].font.hidden = True
doc.paragraphs[0].runs[0].font.italic = True
doc.paragraphs[0].runs[0].font.outline = True
print(doc.paragraphs[0].runs[0].font.size.pt)
doc.paragraphs[0].runs[0].font.size = Pt(18)
doc.paragraphs[0].runs[0].font.name = "幼圆"
doc.paragraphs[0].runs[0].element.rPr.rFonts.set(qn('w:eastAsia'),"幼圆")
doc.paragraphs[0].runs[0].text = "你好呀中国"
doc.save("test1.docx")
|