5个有趣的Python脚本

简介: 5个有趣的Python脚本

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还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。

相关文章
|
10天前
|
存储 Shell 区块链
怎么把Python脚本打包成可执行程序?
该文档介绍了如何将Python脚本及其运行环境打包成EXE可执行文件,以便在不具备Python环境的计算机上运行。首先确保Python脚本能够正常运行,然后通过安装PyInstaller并使用`--onefile`参数将脚本打包成独立的EXE文件。此外,还提供了去除命令行窗口和指定可执行文件图标的详细方法。这些步骤帮助用户轻松地将Python程序分发给最终用户。
怎么把Python脚本打包成可执行程序?
|
4天前
|
安全 JavaScript 前端开发
自动化测试的魔法:如何用Python编写你的第一个测试脚本
【8月更文挑战第41天】在软件的世界里,质量是王道。而自动化测试,就像是维护这个王国的骑士,确保我们的软件产品坚不可摧。本文将引导你进入自动化测试的奇妙世界,教你如何使用Python这把强大的魔法杖,编写出能够守护你代码安全的第一道防护咒语。让我们一起开启这场魔法之旅吧!
|
10天前
|
存储 Java 开发者
python脚本实现原理
【9月更文挑战第4天】python脚本实现原理
25 5
|
7天前
|
运维 监控 API
自动化运维:使用Python脚本进行日常管理
【9月更文挑战第6天】在现代的IT环境中,自动化运维已成为提升效率、减少人为错误的关键。本文将介绍如何通过Python脚本简化日常的运维任务,包括批量配置管理和日志分析。我们将从基础语法讲起,逐步深入到脚本的实际应用,旨在为读者提供一套完整的解决方案,以实现运维工作的自动化和优化。
11 1
|
11天前
|
运维 Linux 测试技术
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第34天】在快节奏的IT环境中,自动化运维成为提升效率、降低错误率的关键。本文以Python脚本为例,展示如何通过编写简单的脚本来自动化日常运维任务,如批量更改文件权限、自动备份数据等。文章不仅提供代码示例,还探讨了自动化运维带来的益处和实施时应注意的问题。
|
12天前
|
运维 监控 网络安全
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第33天】在本文中,我们将深入探讨如何通过Python脚本来自动化执行常见的运维任务。从基础的服务器健康检查到复杂的部署流程,Python因其简洁和功能强大的特性,成为自动化工具的首选。文章将展示编写Python脚本的基本方法,并通过实际示例演示如何应用于真实场景,旨在帮助读者提升效率,减少重复性工作。
|
14天前
|
人工智能 数据挖掘 Python
Python 编程入门:从零基础到编写实用脚本
【8月更文挑战第31天】本文旨在为初学者提供一条清晰的学习路径,帮助他们从零开始掌握Python编程。文章将介绍Python的基础概念、语法规则以及如何通过实际项目来巩固知识。我们将避免枯燥的理论阐述,而是通过具体的代码示例和实用的练习任务,让学习过程既有趣又有成效。无论你是想自动化日常任务,还是渴望进入数据科学领域,这篇文章都将为你开启Python世界的大门。
|
11天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第34天】在数字化时代,高效运维成为企业竞争力的关键。本篇文章将引导你通过Python脚本实现自动化运维,从而提升工作效率和减少人为错误。我们将从简单的文件备份脚本开始,逐步深入到系统监控和自动报告生成,让你的日常工作更加轻松。
|
13天前
|
运维 监控 搜索推荐
自动化运维之宝典:Python脚本实现日常任务管理
在IT运维的日常工作中,重复性任务的自动化处理不仅能提高效率,还能减少人为错误。本文将介绍如何用Python编写简单脚本来自动化常见的运维任务,比如备份文件、监控系统资源和自动更新软件包。我们将一步步构建这些脚本,确保它们易于理解和扩展,最终目标是让读者能够自行定制脚本以适应自己的运维需求。 【8月更文挑战第31天】
|
14天前
|
运维 监控 数据可视化
自动化运维:使用Python脚本进行日志分析
【8月更文挑战第31天】当系统出现问题时,我们通常会查看日志寻找线索。然而,手动阅读大量日志既费时又易出错。本文将介绍如何使用Python脚本自动分析日志,快速定位问题,提高运维效率。我们将从简单的日志读取开始,逐步深入到复杂的正则表达式匹配和错误统计,最后实现一个自动化的日志监控系统。无论你是新手还是老手,这篇文章都将为你提供有价值的参考。让我们一起探索如何用代码解放双手,让运维工作变得更加轻松吧!