边敲代码边学是可以迅速上手滴!
下面是一些基础语法代码,可以参考注释理解:
print('Dad!妈')
print("Hello"+" World"+"!")
print("He said 'good!'")
print('He said "good!"')
print("He said \"good!\"")
print("He said \"Let\'s go!\"")
print("Hello!\nHi!")
print("我是第一行\n我是第二行")
print('''床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。''')
print('''床前明月光,疑是地上霜。
举头望明月,低头思故乡。''')
greet = "您好,吃了么,"
greet_chinese = greet
greet_english = "Yo what's up,"
greet = greet_english
print(greet+"张三")
print(greet+"李四")
print(greet+"王五")
print(greet_chinese+"张三")
"""
import math
a=1
b=9
c=20
delta=b**2-4*a*c
print((-b+math.sqrt(delta))/(2*a))
print((-b-math.sqrt(delta))/(2*a))
"""
# 对字符串求长度
s = "Hello World!"
print(len(s))
# 通过索引获取单个字符
print(s[0])
print(s[11])
print(s[len(s)-1])
# 布尔类型
b1 = True
b2 = False
# 空值类型
n = None
# type函数
print(type(s))
print(type(b1))
print(type(n))
print(type(1.5))
'''
#BMI=体重/(身高**2)
user_weight=float(input("请输入你的体重(单位:kg):"))
user_height=float(input("请输入你的身高(单位:m):"))
user_BMI=user_weight/(user_height)**2
print("你的BMI为:"+str(user_BMI))
'''
# # input输出的全部为string,利用int()
# mood_index = int(input("对象今天的心情指数是:"))
# if mood_index >= 60:
# print("恭喜,今晚应该可以打游戏,去吧皮卡丘!")
# print("haha~")
# else: # mood_index<60
# print("为了自个的小命,还是别打了。")
# #BMI=体重/(身高**2)
# user_weight = float(input("请输入你的体重(单位:kg):"))
# user_height = float(input("请输入你的身高(单位:m):"))
# user_BMI = user_weight / (user_height) ** 2
# print("你的BMI为:"+str(user_BMI))
# if user_BMI <= 18.5:
# print("此BMI值属于偏瘦范围。")
# elif 18.5< user_BMI <= 25:
# print("此BMI值属于正常范围。")
# elif 25 <= user_BMI <= 30:
# print("此BMI属于肥胖范围。")
shopping_list = []
shopping_list.append("键盘")
shopping_list.append("键帽")
shopping_list.append("音箱")
shopping_list.append("电竞椅")
shopping_list.remove("键帽")
shopping_list[1] = "键盘"
print(shopping_list)
print(len(shopping_list))
print(shopping_list[0])
price = [799, 1024, 200, 800]
max_price = max(price)
min_price = min(price)
sorted_price = sorted(price)
print(max_price)
print(min_price)
print(sorted_price)
# # 结合input、字典、if判断,做一个查询流行行语含义的电子词典程序
# slang_dict = {"灰太狼" : "我一定会回来的!",
# "光头强" : "臭狗熊。"}
# slang_dict["熊二"]="熊大,光头强又来砍树了!"
#
# query=input("请输入您想查询的流行语:")
# if query in slang_dict:
# print("您查询的"+query+"含义如下:")
# print(slang_dict[query])
# else:
# print("您查询的流行语未收录。")
# print("当前本词典收录词条为:"+str(len(slang_dict))+"条。")
# # 注意print的类型只能是str
house_work_count = 12
red_envelope_count = 2
shopping_count = 6
has_been_angry = 0
if(house_work_count > 10 and red_envelope_count > 1 and shopping_count > 4 and not has_been_angry):
print("摩拳擦掌等待switch!")
else:
print("switch随风散去......")
list = ["hello"]
list.append(True)
list.append(None)
list.append(66.6)
print(list)
example_list = ["键盘", "键帽"]
example_list.append("显示器")
example_list.remove("显示器")
print(example_list)
contacts = {("张伟", 23): "15000000000",
("张伟", 24): "1510000000",
("张伟", 25): "1520000000"}
zhangwei23_phone = contacts[("张伟", 23)]
print(zhangwei23_phone)
temperature_dict = {"111": 34.6, "112": 36.6, "113": 37, "114": 38.1}
temperature_dict.keys() # 所有键
temperature_dict.values() # 所有值
temperature_dict.items() # 所有键值对
for staff_id, temperature in temperature_dict.items():
if temperature >= 38:
print(staff_id)
for temperature_tuple in temperature_dict.items():
staff_id = temperature_tuple[0]
temperature = temperature_tuple[1]
if temperature >= 38:
print(staff_id)
total = 0
for i in range(1, 101): # (1,101)不包括101这个数,而是到100截止
total = total + i
print("1+2+3+...+100="+str(total))
# for i in rang(100):
# # measure_brightness函数返回当前测量的天空亮度
# if measure_brightness() >= 500:
# take_photo() # 拍照
# # measure_brightness函数返回当前测量的天空亮度
# while measure_brightness() >= 500:
# take_photo() # 拍照
# 三种方法实现循环
list1 = ["你", "好", "吗", "兄", "弟"]
for i in list1:
print(i)
for i in range(len(list1)):
print(list1[i])
i = 0
while i < len(list1):
print(list1[i])
i = i+1
# print("哈喽呀!我是一个求平均值的程序。")
# total = 0
# count = 0
# user_input = input("请输入数字(完成所有数字输入后,请输入q终止程序):")
# while user_input != "q":
# num = float(user_input)
# total += num
# count += 1
# user_input = input("请输入数字(完成所有数字输入后,请输入q终止程序):")
# if count == 0:
# result = 0
# else:
# result = total / count
# print("你输入的数字平均值为"+str(result)) # 注意加str
for i in range(5, 10):
print(i)
for num in range(1, 10, 2):
print(num)
# contacts = ["老余", "老林", "老陈", "老李", "老曾", "老张"]
# for name in contacts:
# message_content = name + ":岁始之乐,点翠化柳喜开颜。 \
# 云开雾散,良辰美景共团圆。祝福" + name + \
# "及家人新年快乐,平安顺遂,虎年大吉!"
# print(message_content)
# # 假如有函数send_message(name, message_content)
contacts = ["老余", "老林", "老陈", "老李", "老曾", "老张"]
year = "虎"
for name in contacts:
message_content = """"
绿回春渐,新元肇启。
新岁甫置,福气东来。
金""" + year + """贺岁,欢乐祥瑞。
金""" + year + """敲门,五福临门。
给""" + name + """及家人拜年啦!
新春快乐,""" + year + """年大吉!
"""
# message_content = """"
# 绿回春渐,新元肇启。
# 新岁甫置,福气东来。
# 金{0}贺岁,欢乐祥瑞。
# 金{0}敲门,五福临门。
# 给{1}及家人拜年啦!
# 新春快乐,{0}年大吉!
# """.format(year, name)
#
# message_content = """"
# 绿回春渐,新元肇启。
# 新岁甫置,福气东来。
# 金{current_year}贺岁,欢乐祥瑞。
# 金{current_year}敲门,五福临门。
# 给{current_name}及家人拜年啦!
# 新春快乐,{current_year}年大吉!
# """.format(current_year = year, current_name = name)
#
# message_content = f""""
# 绿回春渐,新元肇启。
# 新岁甫置,福气东来。
# 金{year}贺岁,欢乐祥瑞。
# 金{year}敲门,五福临门。
# 给{name}及家人拜年啦!
# 新春快乐,{year}年大吉!
# """
print(message_content)
gpa_dict = {"小明": 3.251, "小花": 3.869, "小李": 2.683, "小张": 3.685}
for st in gpa_dict.items():
name = st[0]
gpa = st[1]
print("{0}你好,你的当前绩点为:{1}".format(name, gpa))
gpa_dict = {"小明": 3.251, "小花": 3.869, "小李": 2.683, "小张": 3.685}
for st in gpa_dict.items():
name = st[0]
gpa = st[1]
print("{0}你好,你的当前绩点为:{1:.2f}".format(name, gpa))
gpa_dict = {"小明": 3.251, "小花": 3.869, "小李": 2.683, "小张": 3.685}
for st in gpa_dict.items():
name = st[0]
gpa = st[1]
print(f"{name}你好,你的当前绩点为:{gpa:.2f}")
def calculate_sector(central_angle, radius):
sector_area = central_angle / 360 * 3.14 * radius ** 2
print(f"此扇形的面积为:{sector_area}")
return sector_area
calculate_sector(160, 30)
# BMI=体重/(身高**2)
def calculate_BMI(user_weight, user_height):
user_BMI = user_weight / user_height ** 2
print("你的BMI为:"+str(user_BMI))
if user_BMI <= 18.5:
category = "偏瘦"
elif 18.5 < user_BMI <= 25:
category = "正常"
elif 25 <= user_BMI <= 30:
category = "肥胖"
print(f"你的BMI分类为{category}")
return user_BMI
calculate_BMI(45, 1.64)
# 计算中位数
def median(num_list):
num_list = sorted(num_list)
n = len(num_list)
# 如果一共有奇数个数子,取中间那个
if n % 2 == 1:
return num_list[n // 2]
# 如果一共有偶数个数子,取中间那两个的平均值
else:
return (num_list[n // 2 - 1] + num_list[n // 2]) / 2
print(median([69, 124, -32, 27, 217]))
import statistics
print(statistics.median([69, 124, -32, 27, 217]))
# 引入模块的3种方法
# import 语句
import statistics
print(statistics.median([19, -5, 36]))
print(statistics.mean([19, -5, 36]))
# from...import... 语句
from statistics import median, mean
print(median([19, -5, 36]))
print(mean([19, -5, 36]))
# from...import * 语句
from statistics import *
print(median([19, -5, 36]))
print(mean([19, -5, 36]))
# 定义ATM类
class ATM:
def __init__(self, 编号, 银行, 支行):
self.编号 = 编号
self.银行 = 银行
self.支行 = 支行
# 创建两个ATM对象
atm1 = ATM("001", "招商银行", "南园支行")
atm2 = ATM("002", "中国银行", "北园支行")
# 定义纸币类
class 纸币:
# __init__ 类似于构造函数
def __init__(self, 编号, 面值, 发行年份):
self.编号 = 编号
self.面值 = 面值
self.发行年份 = 发行年份
# 创建两个纸币对象
纸币1 = 纸币("AA00000000", 50, "2015")
纸币2 = 纸币("AA00000001", 100, "2020")
print(atm1.编号)
print(纸币1.编号)
# def 打印记录(交易类型, 面值, ATM编号, 银行, 纸币编号, 支行, 发行年份):
# def 存钱(ATM对象, 纸币对象):
# print("存钱", ATM对象, 纸币对象)
# def 取钱(ATM对象, 纸币对象):
# print("取钱", ATM对象, 纸币对象)
#
# 存钱(atm1, 纸币1)
# 取钱(atm2, 纸币2)
#
# class 洗衣机:
# def __init__(self, 容量):
# self.容量 = 容量
# def 清洗(self, 需清洗物品):
# # 需要通过容量计算烘干时长
# 洗衣机容量 = self.容量
# def 烘干(self, 需烘干物品):
# # 需要通过容量计算烘干时长
# 洗衣机容量 = self.容量
#
# class 学生:
# def __init__(self, 学号, 年级):
# self.学号 = 学号
# self.年级 = 年级
# def 去学校(self, 学校):
# 定义House类
class House:
def __inif__(self, 颜色, 位置, 卧室数):
self.颜色 = 颜色
self.位置 = 位置
self.卧室数 = 卧室数
# 创建两个House对象
house1 = ("紫色", "长沙", 4)
house2 = ("红色", "深圳", 3)
print(house1)
print(house2)
class CuteCat:
def __init__(self, cat_name, cat_age, cat_color):
self.name = cat_name
self.age = cat_age
self.color = cat_color
def speak(self):
print("喵" * self.age)
def think(self, content):
print(f"小猫{cat1.name}在思考{content}")
cat1 = CuteCat("Lambton", 4, "白色")
print(f"小猫{cat1.name}的年龄是{cat1.age}岁,花色是{cat1.color}")
cat1.speak()
cat1.think("现在去抓沙发还是撕纸箱?")
# 定义一个学生类
# 要求:
# 1.属性包括学生姓名、学号,以及语数英三科的成绩
# 2.能够设置学生某课的成绩
# 3.能够打印出该学生的所有科目成绩
class Student:
def __init__(self, name, id):
self.name = name
self.id = id
self.grades = {"语文": 0, "数学": 0, "英语": 0}
def set_grade(self, course, grade):
if course in self.grades:
self.grades[course] = grade
def print_grades(self):
print(f"学生{self.name}(学号:{self.id})的成绩为:")
for course in self.grades:
print(f"{course}:{self.grades[course]}分")
cheng = Student("小陈", "100618")
zeng = Student("小曾", "100622")
zeng.set_grade("数学", 95)
zeng.set_grade("语文", 85)
zeng.set_grade("英语", 93)
print(cheng.name)
print(zeng.grades)
zeng.print_grades()
class Mammal:
def __init__(self, name, sex):
self.name = name
self.sex = sex
self.num_eyes = 2
def breathe(self):
print(self.name + "在呼吸.....")
def poop(self):
print(self.name + "在拉屎.....")
class Human(Mammal):
def __init__(self, name, sex):
super().__init__(name, sex)
self.has_tail = False
def read(self):
print(self.name + "在阅读.....")
class Cat(Mammal):
def __init__(self, name, sex):
super().__init__(name, sex)
self.has_tail = True
def scratch_sofa(self):
print(self.name + "在抓沙发.....")
cat1 = Cat("Jojoi", "男")
print(cat1.name)
cat1.poop()
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def print_info(self):
print(f"员工{self.name}的工号为:{self.id}")
class FullTimeEmployee(Employee):
def __init__(self, name, id, monthly_salary):
super().__init__(name, id)
self.monthly_salary = monthly_salary
def calculate_monthly_pay(self):
return self.monthly_salary
class PartTimeEmployee(Employee):
def __init__(self, name, id, daily_salary, work_days):
super().__init__(name, id)
self.daily_salary = daily_salary
self.work_days = work_days
def calculate_monthly_pay(self):
return self.daily_salary * self.work_days
张三 = FullTimeEmployee("张三", "1001", 6000)
李四 = PartTimeEmployee("李四", "1002", 230, 15)
张三.print_info()
李四.print_info()
print(张三.calculate_monthly_pay())
print(李四.calculate_monthly_pay())
import numpy as np
import matplotlib.pyplot as plt
test = np.array([[1, 2, 3], [2, 3, 4]]) # 定义数组
print(test)
# 打印数组[[1 2 3]
# [2 3 4]]
# ndarray的属性
print(test.shape) # 打印数组的维度为两行三列:(2, 3)
print(test.ndim) # 打印数组的维数是二维:2
print(test.size) # 打印数组的元素个数,有6个数:6
print(test.itemsize) # 打印数组中元素的长度(字节),为八个字节:4
print(test.dtype) # 打印数组中元素的类型,1、2、3、4:int32
# 生成数组的方法
# 1.
# np.ones(shape, dtype)
# np.ones_like(a, dtype)
# np.zeros(shape, dtype)
# np.zeros_like(a, dtype)
a = np.ones((3, 4))
print(a)
b = np.zeros_like(a)
print(b)
c = np.zeros((2, 5))
print(c)
d = np.ones_like(c)
print(d)
# 2.从现有的数组中生成
# a = np.array[[1,2,3],[4,5,6]]
# a1 = np.array(a)深拷贝
# a2 = np.asarray(a)浅拷贝
e = np.array(test)
print(e)
f = np.asarray(test)
print(f)
test[0][0] = 5
print(e)
print(f)
# 3.生成固定范围的数组,区间左开右闭
a1 = np.linspace(0, 100, 10) # 从0到100,生成10个数数
a2 = np.arange(10, 50, 2) # 从10开始到50,步长为2
a3 = np.logspace(0, 2, 5) # 10的0次方到10的2次方(1~100),生成5个数
print(a1, a2, a3)
# 4.生成随机数组
# (1)正态分布
# b1 = np.random.normal(1.75, 1, 100000000) # 均值为1.75,标准差为1的正态分布数据100000000个
# 使用直方图观察数据分布
# (2)均匀分布
# b2 = np.random.uniform(-1, 1, 100000000) # -1到1之间100000000个数据均匀分布
# 使用直方图观察数据分布
# print(b1, b2)
print(np.random.uniform(15, 18))
# 利用图像查看np.random.uniform(-1, 1, 100000000)是不是正态分布
# import matplotlib.pyplot as pit
# x = np.random.uniform(-1, 1, 100000000)
# y = np.random.normal(1.75, 1, 100000000)
# 创建画布
# plt.figure(figsize=(10, 10), dpi=100)
# 绘制折线图
# plt.plot(x, 100)
# plt.plot([1, 2, 3, 4, 5], [18, 17, 11, 9, 10])
# 绘制柱状图
# plt.hist(x, 1000) # 分成1000组,每个组100000条数据,基本上都是均匀分布
# plt.hist(y, 1000) # 分成1000组,每个组100000条数据,基本上都是正态分布
# 显示图像
# plt.show()
# 6.数组中元素的获取
array1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
print(array1)
print(array1[:1, :]) # [[1 2 3 4]] 输出第0行下标为空,到第1行下标为1中的所有列
print(array1[1:4, 1:3]) # [[ 6 7] 输出2、3、4行的2、3列(不包括第一行和第一列)
# [10 11]
# [14 15]]
# 7.形状修改
# reshape
print(test.shape)
print(test.reshape(1, 6))
print(test)
# resize
test = np.resize(test, (1, 6))
print(test)
# T # 转置,行列进行互换 resize和reshape的区别:resize是对值本身进行修改
test = test.T # 转置
print(test) # 三行两列,第一行变第一列,第二行变第二列
# 8.数组的去重
temp = np.array([[1, 2, 3, 4], [3, 4, 5, 6]])
temp = np.unique(temp)
print(temp)
# 9.逻辑运算
score = np.random.randint(40, 100, (10, 5)) # 在40到100生成随机数,shape为10行5列
test_score = score[6:, 0:5] # 从第六行后面开始的所有列,以及前五列(第一到第五列)
print(score)
print(test_score)
print(test_score > 60) # 大于60的元素位置为True,否则为False
test_score[test_score > 60] = 1 # 大于60的元素位置为1,否则为原值
print(test_score)
# 10.通用判断函数
print(score[0:2, :])
print(np.all(score[0:2, :] > 60)) # 所有元素都大于60才返回True,否则都为False
print(score[0:2, :])
print(np.any(score[0:2, :] > 90)) # 只要有一个元素大于90就返回True,否则都为False
# 11.where三元运算符
temp1 = score[:4, :4]
print(temp1)
print(np.where(temp1 > 60, 1, 0)) # 大于60的元素的位置为1,小于60的元素的位置为0
# 12.统计运算
# min max mean argmin argmax
# 13.数组间的运算
aa = np.array([[1, 2, 3], [3, 4, 5]])
print(aa + 3)
print(aa / 2)
print(aa * 3)
# 14.矩阵
# 逆:如果两个矩阵相乘,得到一个单位矩阵,则两个矩阵互为逆
# 转置:矩阵的行列互换T
# 实例:矩阵运算
# np.matmul 支持乘以一个矩阵,不支持乘以一个数
# no.dot 支持乘以一个矩阵,支持乘以一个数
bb = np.array([[80, 86], [82, 80], [85, 78], [90, 90], [86, 82], [82, 90], [78, 80], [92, 94]])
cc = np.array([[0.7], [0.3]])
print(np.matmul(bb, cc))
print(np.dot(bb, cc))
dd = 2
print(np.dot(bb, dd))
# print(np.matmul(bb, dd)) # 报错
# # 利用图像查看np.random.uniform(-1, 1, 100000000)是不是正态分布
# x = np.random.uniform(-1, 1, 100000000)
# y = np.random.normal(1.75, 1, 100000000)
# # 创建画布
# plt.figure(figsize=(10, 10), dpi=100)
# # 绘制折线图
# # plt.plot(x, 100)
# # plt.plot([1, 2, 3, 4, 5], [18, 17, 11, 9, 10])
# # 绘制柱状图
# plt.hist(x, 1000) # 分成1000组,每个组100000条数据,基本上都是均匀分布
# plt.show()
# plt.hist(y, 1000) # 分成1000组,每个组100000条数据,基本上都是正态分布
# # 显示图像
# plt.show()
# list属性
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = ['aaa', 1, 3.14, 'love you', [1, 2, 3]]
# 判断数据类型
print(type(list1))
# 列表元素个数
print(len(list2))
# 从列表最后面插入元素
list1.append(1)
print(list1)
# 插入多个元素
list1.extend([2, 1])
print(list1)
# 在指定位置插入数值
list1.insert(2, 8)
print(list1)
# 替换元素
list1[1] = 0
print(list1)
# 删除指定位置的元素
list1.pop(2)
print(list1)
# 删除列表的指定元素
list1.remove(5)
print(list1)
# 清空列表
# list1.clear()
# 删除列表
del(list2)
# 查找成员的下标,后面是下标范围
print(list1.index(9, 2, 8))
# 统计成员的出现次数
print(list1.count(1))
# 返回最大值
print(max(list1))
# 返回最小值
print(min(list1))
# 颠倒所有元素
list1.reverse()
print(list1)
# 列表排序,False升序
list1.sort(reverse=True)
print(list1)
# a必须为字符串
# a = "[1, 2, 3]"
# a = a.replace('[', '')
# a = a.replace(']', '')
# print(a)
# import numpy as np
# print(np.zeros(256,dtype=int))
# imatx = 20
# imaty = 20
# ran_array = np.random.randint(0, 256, (imatx, imaty))
# img_array = np.ones_like(ran_array)
# img_array[:1, :] = 0
# img_array[imatx-1:, :] = 0
# img_array[:, :1] = 0
# img_array[:, imaty-1:] = 0
# print(img_array)
import os
# 文件的读取
# "r"读取模式(只读)
# "r+"同时支持读写文件
# "w"写入模式(只写)
# "a"附加模式
f = open("./data.txt", "r", encoding="utf-8")
content1 = f.read()
print(content1)
f.close()
# 使用下列格式时,可以自动关闭文件,但是记得要缩进。如果没有缩进文件就以及关闭
with open("./data.txt", "r", encoding="utf-8") as f:
content2 = f.read()
print(content2)
# readline()函数读取文件的一行,再次调用该函数从下一行继续读取
with open("./data.txt", "r", encoding="utf-8") as f:
print(f.readline())
print(f.readline())
# readlines()函数调用以后返回一个列表,列表中的每一个元素为一行的内容,换行符号'\n'也被读进去
# readlines()一般结合for()循环使用
with open("./data.txt", "r", encoding="utf-8") as f:
print(f.readlines())
# 注意只能读取文件一次,此时文件已经读取到末尾,再次读取为空
with open("./data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line)
# "w"和"a"模式在打开文件不存在的情况下,都在自动创建新的文件
# 写一个新的文件poem.txt
with open("./poem.txt", "w", encoding="utf-8") as a:
a.write("我欲乘风归去,\n")
a.write("又恐琼楼玉宇,\n")
a.write("高处不胜寒。\n")
with open("./poem.txt", "a", encoding="utf-8") as a:
a.write("起舞弄清影,\n")
a.write("何似在人间。\n")
# 先read()读取文件到最后一行,再在最后一行追加write()写入新的数据
with open("./poem.txt", "r+", encoding="utf-8") as a:
print(a.read())
a.write("--《水调歌头》苏轼\n")
print(a.read())
# 为什么不能输出新加入的数据
# 分割字符串的三种方法
# 1.split()
s = "C:/Users/34163/Desktop/A/A_0000_AA.txt"
print(s.split("\\")[-1]) # C:/Users/34163/Desktop/A/A_0000_AA.txt
print(s.split("\\")) # ['C:/Users/34163/Desktop/A/A_0000_AA.txt']
s = r"C:\Users\34163\Desktop\A\A_0000_AA.txt"
print(s.split("\\")[-1]) # A_0000_AA.txt
print(s.split("\\")) # ['C:', 'Users', '34163', 'Desktop', 'A', 'A_0000_AA.txt']
print('\n')
# 2.rfind()
s = r"C:\Users\34163\Desktop\A\A_0000_AA.txt"
n = s.rfind("\\")
# rfind()返回字符串“\\”最后一次出现的索引即为n,没有时返回-1
# find()返回字符串第一次出现的索引,没有时返回-1
print(s[(n + 1):]) # A_0000_AA.txt
# 从索引为n的分割符号'\'开始,输出后面的字符串
print(s[:n]) # C:\Users\34163\Desktop\A
# 从字符串的最前面开始,输出到最后一个字符串"\\"
print('\n')
# 3.os.path.basename() 记得import os
s = r"C:\Users\34163\Desktop\A\A_0000_AA.txt"
print(os.path.dirname(s)) # C:\Users\34163\Desktop\A
print(os.path.basename(s)) # A_0000_AA.txt
# 遍历文件夹下的所有文件
path = r'C:\Users\34163\Desktop\A'
dirs = os.listdir(path)
for dir in dirs:
print("子文件:", dir)
print("子文件名称:", dir.split(".")[0])
print("子文件路径:", os.path.join(path, dir))
print("*" * 50)
# .join()将序列中的元素用指定符号连接成字符串,注意最前面有'.'
a = ['i', 'love', 'china', '!'] # a为列表
print(' '.join(a)) # i love china !
print('_'.join(a)) # i_love_china_!
print('*'.join(a), '\n') # i*love*china*!
b = "i love china!" # b为字符串
print(' '.join(b)) # i l o v e c h i n a !
print('_'.join(b)) # i_ _l_o_v_e_ _c_h_i_n_a_!
print('*'.join(b), '\n') # i* *l*o*v*e* *c*h*i*n*a*!
c = ('i', 'love', 'china', '!') # c为元组
print(' '.join(c)) # i love china !
print('-'.join(c), '\n') # i-love-china-!
d1 = {'i': 1, 'love': 2, 'china': 3} # d1为字典,字典的读取是随机的,输出结果不唯一
print(' '.join(d1)) # i love china
print('-'.join(d1), '\n') # i-love-china
d2 = {'i': 2, 'love': 1, 'china': 0} # d2为字典,字典的读取是随机的,输出结果不唯
print(' '.join(d2)) # i love china
print('-'.join(d2), '\n') # i-love-china
# os.path.join()将多个路径拼接,称为合并目录,注意输出结果不同
filename = os.path.join('C:/Users/34163/', 'Desktop/A/', 'A_003_AA.txt')
print(filename) # C:/Users/34163/Desktop/A/A_003_AA.txt
filename = os.path.join('C:/Users/34163/', 'Desktop/A', 'A_003_AA.txt')
print(filename,'\n') # C:/Users/34163/Desktop/A\A_003_AA.txt
# 为什么不能实现遍历?自己解决了问题
a = 'C:/Users/34163/Desktop/A/'
for root, dirs, files in os.walk(a):
print(root) # root为当前遍历文件夹的地址
print(dirs) # dirs为list,存放文件夹中所有目录的名称
print(files, '\n') # files为list,存放文件夹中所有文件
for file in files:
print(file)
path = os.path.join(root, file)
print(path)
# for dir in dirs: # A文件夹中无子目录(文件夹),所以不能进入循环
# print(dir)
# path = os.path.join(root, dir)
# print(path)
import cv2 # opencv读取格式是BGR
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline # 展示图像方便,不需要调用:plt.show()
img = cv2.imread('psc (13).jpg', cv2.IMREAD_COLOR)
# 创建mask
mask = np.zeros(img.shape[:2], np.uint8)
print(mask.shape)
mask[100:600, 100:800] = 255 # 规定mask=255
# 显示掩码
# cv2.namedWindow('image', 0)
# cv2.imshow('image', mask)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
def cv_show(name, img):
cv2.namedWindow('image', 0)
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# cv_show('image', mask)
# cv_show('image', img)
# 与操作,将掩码与原图相与得到masked_img。255部分为白色,其他部分为0。
masked_img = cv2.bitwise_and(img, img, mask=mask)
cv_show('image', masked_img)
# hist_full = cv2.calcHist([img], [0], None, [256], [0, 256])
# hist_mask = cv2.calcHist([img], [0], mask, [256], [0, 256])
# # cv2.namedWindow('gray', 1)
# plt.subplot(221)
# plt.imshow(img, 'gray')
# plt.subplot(222)
# plt.imshow(mask, 'gray')
# plt.subplot(223)
# plt.imshow(masked_img, 'gray')
# plt.subplot(224)
# plt.plot(hist_full)
# plt.plot(hist_mask)
# plt.xlim([0, 256]) # 设置X轴的边界为0~255,同理有plt.ylim()
# plt.show()
# plt.hist(img.ravel(), 256)
# plt.show()
# equ = cv2.equalizeHist(img)
# plt.hist(equ.ravel(), 256)
# plt.show() # 报错