5个有趣的Python脚本(python脚本例子)
ztj100 2024-11-08 15:06 17 浏览 0 评论
Python可以玩的方向有很多,比如爬虫、预测分析、GUI、自动化、图像处理、可视化等等,可能只需要十几行代码就能实现酷炫的功能。
因为Python是动态脚本语言,所以代码逻辑比Java要简要很多,实现同样的功能少写很多代码。而且Python生态有众多的第三方工具库,把功能都封装在包里,只需要你调用接口,就能使用复杂的功能。
下面举几个简单好玩的脚本例子,初学者可以照着代码写写,能快速掌握python语法。
1、使用PIL、Matplotlib、Numpy对模糊老照片进行修复
# encoding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os.path
# 读取图片
img_path = "E:\\test.jpg"
img = Image.open(img_path)
# 图像转化为numpy数组
img = np.asarray(img)
flat = img.flatten()
# 创建函数
def get_histogram(image, bins):
# array with size of bins, set to zeros
histogram = np.zeros(bins)
# loop through pixels and sum up counts of pixels
for pixel in image:
histogram[pixel] += 1
# return our final result
return histogram
# execute our histogram function
hist = get_histogram(flat, 256)
# execute the fn
cs = np.cumsum(hist)
# numerator & denomenator
nj = (cs - cs.min()) * 255
N = cs.max() - cs.min()
# re-normalize the cumsum
cs = nj / N
# cast it back to uint8 since we can't use floating point values in images
cs = cs.astype('uint8')
# get the value from cumulative sum for every index in flat, and set that as img_new
img_new = cs[flat]
# put array back into original shape since we flattened it
img_new = np.reshape(img_new, img.shape)
# set up side-by-side image display
fig = plt.figure()
fig.set_figheight(15)
fig.set_figwidth(15)
# display the real image
fig.add_subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Image 'Before' Contrast Adjustment")
# display the new image
fig.add_subplot(1, 2, 2)
plt.imshow(img_new, cmap='gray')
plt.title("Image 'After' Contrast Adjustment")
filename = os.path.basename(img_path)
# plt.savefig("E:\\" + filename)
plt.show()
2、将文件批量压缩,使用zipfile库
import os
import zipfile
from random import randrange
def zip_dir(path, zip_handler):
for root, dirs, files in os.walk(path):
for file in files:
zip_handler.write(os.path.join(root, file))
if __name__ == '__main__':
to_zip = input("""
Enter the name of the folder you want to zip
(N.B.: The folder name should not contain blank spaces)
>
""")
to_zip = to_zip.strip() + "/"
zip_file_name = f'zip{randrange(0,10000)}.zip'
zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
zip_dir(to_zip, zip_file)
zip_file.close()
print(f'File Saved as {zip_file_name}')
3、使用tkinter制作计算器GUI
tkinter是python自带的GUI库,适合初学者练手创建小软件
import tkinter as tk
root = tk.Tk() # Main box window
root.title("Standard Calculator") # Title shown at the title bar
root.resizable(0, 0) # disabling the resizeing of the window
# Creating an entry field:
e = tk.Entry(root,
width=35,
bg='#f0ffff',
fg='black',
borderwidth=5,
justify='right',
font='Calibri 15')
e.grid(row=0, column=0, columnspan=3, padx=12, pady=12)
def buttonClick(num): # function for clicking
temp = e.get(
) # temporary varibale to store the current input in the screen
e.delete(0, tk.END) # clearing the screen from index 0 to END
e.insert(0, temp + num) # inserting the incoming number input
def buttonClear(): # function for clearing
e.delete(0, tk.END)
# 代码过长,部分略
4、PDF转换为Word文件
使用pdf2docx库,可以将PDF文件转为Word格式
from pdf2docx import Converter
import os
import sys
# Take PDF's path as input
pdf = input("Enter the path to your file: ")
assert os.path.exists(pdf), "File not found at, "+str(pdf)
f = open(pdf,'r+')
#Ask for custom name for the word doc
doc_name_choice = input("Do you want to give a custom name to your file ?(Y/N)")
if(doc_name_choice == 'Y' or doc_name_choice == 'y'):
# User input
doc_name = input("Enter the custom name : ")+".docx"
else:
# Use the same name as pdf
# Get the file name from the path provided by the user
pdf_name = os.path.basename(pdf)
# Get the name without the extension .pdf
doc_name = os.path.splitext(pdf_name)[0] + ".docx"
# Convert PDF to Word
cv = Converter(pdf)
#Path to the directory
path = os.path.dirname(pdf)
cv.convert(os.path.join(path, "", doc_name) , start=0, end=None)
print("Word doc created!")
cv.close()
5、Python自动发送邮件
使用smtplib和email库可以实现脚本发送邮件
import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header
# SMTP服务器,这里使用163邮箱
mail_host = "smtp.163.com"
# 发件人邮箱
mail_sender = "******@163.com"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "********"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["******@qq.com","******@outlook.com"]
mm = MIMEMultipart('related')
# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<******@163.com>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')
# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
# 二进制读取图片
image_data = open('a.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)
# 构造附件
atta = MIMEText(open('sample.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)
# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
stp.connect(mail_host, 25)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()
小结
Python还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。
相关推荐
- 如何将数据仓库迁移到阿里云 AnalyticDB for PostgreSQL
-
阿里云AnalyticDBforPostgreSQL(以下简称ADBPG,即原HybridDBforPostgreSQL)为基于PostgreSQL内核的MPP架构的实时数据仓库服务,可以...
- Python数据分析:探索性分析
-
写在前面如果你忘记了前面的文章,可以看看加深印象:Python数据处理...
- C++基础语法梳理:算法丨十大排序算法(二)
-
本期是C++基础语法分享的第十六节,今天给大家来梳理一下十大排序算法后五个!归并排序...
- C 语言的标准库有哪些
-
C语言的标准库并不是一个单一的实体,而是由一系列头文件(headerfiles)组成的集合。每个头文件声明了一组相关的函数、宏、类型和常量。程序员通过在代码中使用#include<...
- [深度学习] ncnn安装和调用基础教程
-
1介绍ncnn是腾讯开发的一个为手机端极致优化的高性能神经网络前向计算框架,无第三方依赖,跨平台,但是通常都需要protobuf和opencv。ncnn目前已在腾讯多款应用中使用,如QQ,Qzon...
- 用rust实现经典的冒泡排序和快速排序
-
1.假设待排序数组如下letmutarr=[5,3,8,4,2,7,1];...
- ncnn+PPYOLOv2首次结合!全网最详细代码解读来了
-
编辑:好困LRS【新智元导读】今天给大家安利一个宝藏仓库miemiedetection,该仓库集合了PPYOLO、PPYOLOv2、PPYOLOE三个算法pytorch实现三合一,其中的PPYOL...
- C++特性使用建议
-
1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...
- Qt4/5升级到Qt6吐血经验总结V202308
-
00:直观总结增加了很多轮子,同时原有模块拆分的也更细致,估计为了方便拓展个管理。把一些过度封装的东西移除了(比如同样的功能有多个函数),保证了只有一个函数执行该功能。把一些Qt5中兼容Qt4的方法废...
- 到底什么是C++11新特性,请看下文
-
C++11是一个比较大的更新,引入了很多新特性,以下是对这些特性的详细解释,帮助您快速理解C++11的内容1.自动类型推导(auto和decltype)...
- 掌握C++11这些特性,代码简洁性、安全性和性能轻松跃升!
-
C++11(又称C++0x)是C++编程语言的一次重大更新,引入了许多新特性,显著提升了代码简洁性、安全性和性能。以下是主要特性的分类介绍及示例:一、核心语言特性1.自动类型推导(auto)编译器自...
- 经典算法——凸包算法
-
凸包算法(ConvexHull)一、概念与问题描述凸包是指在平面上给定一组点,找到包含这些点的最小面积或最小周长的凸多边形。这个多边形没有任何内凹部分,即从一个多边形内的任意一点画一条线到多边形边界...
- 一起学习c++11——c++11中的新增的容器
-
c++11新增的容器1:array当时的初衷是希望提供一个在栈上分配的,定长数组,而且可以使用stl中的模板算法。array的用法如下:#include<string>#includ...
- C++ 编程中的一些最佳实践
-
1.遵循代码简洁原则尽量避免冗余代码,通过模块化设计、清晰的命名和良好的结构,让代码更易于阅读和维护...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)