一天 - 糟糕,CSV,matplotlib
>面向对象的编程(oops):
oops代表面向对象的编程系统,该系统是基于对象概念的编程范式。
类:
>用于创建对象的蓝图或模板。>类代表逻辑实体。
对象:
对象代表类。对象是班级的代表。
对象是类的实例。
对象代表现实世界实体或实时实体。
对象具有状态和行为。
自行车类定义了自行车是什么,它可以做什么。
>品牌,颜色和速度等状态描述了自行车。诸如开始,加速和停止诸如自行车可以执行的操作之类的行为。activa和踏板车是自行车类的对象。
每个对象代表具有特定状态(例如品牌和颜色)和行为的真实自行车。
这是我们在python中使用oop的一些关键原因:>
>代码重新求解
可维护性
- >示例:
from pil import imagephoto = image.open("/home/prigo/documents/python_class/images.jpeg")photo.show()
>
> csv文件代表一行,行中的每个值都通过逗号分隔。csv文件看起来像excel,但仅在excel软件中打开excel文件。>csv文件用于所有操作系统。>
>我们可以以以下两种格式打开csv文件。>
f =open("sample.txt", "r")with open("sample.txt",’r’) as f:
r-read
打开读取文件。文件必须存在。
w-write 打开撰写文件。创建一个新文件或覆盖现有的文件。
>
> rb-read二进制 这用于读取二进制文件,例如图像,视频,音频文件,pdf或任何非文本文件。
:>常见的情节类型:
线图:有益于随着时间的推移显示趋势。>
条形图:可用于比较离散值。
直方图:显示了数据集的分布。>
散点图:显示了两个变量之间的关系。>饼图:
用于显示整体的比例。>csv和matplotlib的
>sales.csv
年,销售2020,100002021,8000
2022,95002023,105002024,12000
import matplotlib.pyplot as pltimport csvyears = []sales = []with open("sales.csv","r") as f: reader = csv.reader(f) next(reader) for each_row in reader: years.append(int(each_row[0])) sales.append(int(each_row[1]))print(years)print(sales)plt.figure(figsize =(7,5))plt.plot(years, sales, color="r", label="yearly sales")plt.xlabel('years')plt.ylabel("sales")plt.title("last 5 years sales ")plt.show()
输出:
[2020, 2021, 2022, 2023, 2024][10000, 8000, 9500, 10500, 12000]
我们提供的代码在写入模式(“ w”)中打开文件abcd.txt,并打印出与文件对象f。
的各种属性
f = open("abcd.txt","w")print(type(f))print(f.name)print(f.mode)print(f.readable())print(f.writable())print(f.closed)
输出:
>
abcd.txt
falsetrue
false
>我们正在以写入模式打开文件abcd.txt(“ w”),在文件上写两个字符串(“星期五”和“星期六”),然后关闭文件。
f = open("abcd.txt","w")f.write("friday")f.write("saturday")f.close()
>
f = open("abcd.txt","w")f.write("friday")f.write("saturday")f.close()
> sundaymon day
在附加模式下,该文件不会被覆盖;相反,将新内容添加到文件的末尾。如果不存在该文件,将创建它。
>
f = open("abcd.txt","a")f.write("tuesday")f.write("wednesday")f.close()
> sundaymon daytuesdaywednesday
>
f = open("abcd.txt","r")data = f.read()print(data)f.close()
> sundaymon daytuesdaywedneswednesdayjanjanfebmar
f = open("abcd.txt","r")data = f.read(5)print(data)f.close()
readline()方法从文件中读取字符,直到遇到newline字符(n)或到达文件的末尾。
f = open("abcd.txt","r")data = f.readline()print(data)f.close()
f = open("abcd.txt","r")data = f.readlines()for every_line in data: print(every_line, end='')f.close()
星期五
星期六
>编写一个程序以找到编号。线,文本文件中的字母编号和编号:
玫瑰是一朵美丽的花
快乐的一天
f = open("abcd.txt","r")data = f.readlines()word=0letter=0for each_line in data: line=len(data) words=each_line.split() word=word+len(words) for letters in words: letter=letter+len(letters)print("no.of.lines:" ,line)print("no.of.words:" ,word)print("no.of.words:" ,letter) f.close()
输出:
words编号:10
words:43>编写一个程序以检查给定文件是否可用:>
import osfile_name = input("Enter file Name")if os.path.isfile(file_name): print("File is present") f = open(file_name, "r")else: print("File is not present")
输出:
>输入文件名/home/home/prigo/documents/python_class/abcd.txt文件存在