您当前的位置:首页 > 电脑百科 > 程序开发 > 语言 > Python

5个有趣的Python脚本

时间:2022-10-10 14:47:21  来源:今日头条  作者:Python大数据分析

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



Tags:Python脚本   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
Python可以玩的方向有很多,比如爬虫、预测分析、GUI、自动化、图像处理、可视化等等,可能只需要十几行代码就能实现酷炫的功能。因为Python是动态脚本语言,所以代码逻辑比Java...【详细内容】
2022-10-10  Tags: Python脚本  点击:(0)  评论:(0)  加入收藏
在日常的生活和工作中,我们经常会遇到一些大小问题,其中有很多的问题,都是可以使用一些简单的Python代码就能解决。 比如不久前的复旦大佬,用130行Python代码硬核搞定核酸统计,大...【详细内容】
2022-05-24  Tags: Python脚本  点击:(144)  评论:(0)  加入收藏
扼要:1、学会搭建monkeyrunner开发环境;2、学会使用monkeyrunner+python进行编写脚本;monkeyrunner是Android SDK自带的一个黑盒自动化测试工具。其支持java、python两种语言。...【详细内容】
2021-04-06  Tags: Python脚本  点击:(354)  评论:(0)  加入收藏
自从新个税计税后,每个月发工资你是否真的清楚如何扣税的?今天跟大家分享下如何计算,希望大家喜欢。计税方法科普 这里需要知道两个计算的点: 个税起征点调到 5000; 累积预扣法:税...【详细内容】
2020-08-10  Tags: Python脚本  点击:(428)  评论:(0)  加入收藏
如果有人告诉您可以使用150-200行代码创建交互式Web应用程序,该怎么办? 有趣的权利。 Streamlit为您提供了使用简单的python脚本和一些streamlit调用来创建漂亮的Web应用程序...【详细内容】
2020-06-16  Tags: Python脚本  点击:(849)  评论:(0)  加入收藏
提出需求现在有这样的需求:全网的监控骨干设备及VPN骨干设备都要新增SSH配置(开通SSH登录),涉及到的网络设备上百台,若一台台登录到设备上去配置,想想工作量都巨大。那么Python的...【详细内容】
2020-05-07  Tags: Python脚本  点击:(123)  评论:(0)  加入收藏
B站在小视频功能处提供了 API 接口,今天的任务爬取Bilibili视频~B 站视频网址:https://vc.bilibili.com/p/eden/rank#/?tab=全部 此次爬取视频,我们爬取前100个~我们做好前期...【详细内容】
2019-11-27  Tags: Python脚本  点击:(199)  评论:(0)  加入收藏
前言群里看到有人询问:谁会用python将微信音频文件后缀m4a格式转成mp3格式,毫不犹豫回了句:我会。然后就私下聊起来了解决方法介绍如下:工具:windows系统,python2.7,转换库ffmpeg...【详细内容】
2019-10-08  Tags: Python脚本  点击:(319)  评论:(0)  加入收藏
▌简易百科推荐
Python可以玩的方向有很多,比如爬虫、预测分析、GUI、自动化、图像处理、可视化等等,可能只需要十几行代码就能实现酷炫的功能。因为Python是动态脚本语言,所以代码逻辑比Java...【详细内容】
2022-10-10  Python大数据分析  今日头条  Tags:Python脚本   点击:(0)  评论:(0)  加入收藏
关于日期处理,Python 提供了许多库,例如标准库 datetime、第三方库 dateutil、 Arrow 等。在这篇文章中,我想介绍我个人最喜欢的库pendulum,它使用非常方便,它可以满足任何日期...【详细内容】
2022-10-10  喜欢编码的社畜  今日头条  Tags:pendulum   点击:(15)  评论:(0)  加入收藏
在本文中,我将我的一些笔记变成了20 个面试问题,涵盖了数据结构、核心编程概念和 Python 最佳实践。希望你能完成其中的一些并重温你的 python 技能。事不宜迟,让我们直接进...【详细内容】
2022-10-08  喜欢编码的社畜  今日头条  Tags:Python   点击:(14)  评论:(0)  加入收藏
Android应用自适应多分辨率解决方案2022新版Scrapy打造搜索引擎 畅销4年的Python分布式爬虫download:https://www.51xuebc.com/thread-494-1-1.html1.第一步是创建多个布局文...【详细内容】
2022-10-07  石哥学长  网易号  Tags:Scrapy   点击:(15)  评论:(0)  加入收藏
一、操作文件的函数/方法在Python中要操作文件需要记住1个函数和3个方法:序号函数/方法说明01open打开文件,并且返回文件操作对象02read将文件内容读取到内存03write将制定内...【详细内容】
2022-10-07  python自学网  今日头条  Tags:Python   点击:(32)  评论:(0)  加入收藏
自己电脑上有完整的python环境,所以偶尔写个小工具什么的都很easy,直接命令行run一波就OK,但是如果需要再朋友的电脑上运行,帮别人写了一个小工具,他没有运行环境,就很麻烦。不能...【详细内容】
2022-10-06  大橙子打游戏  掘金  Tags:Python   点击:(19)  评论:(0)  加入收藏
上期有提到自己用Python编写了检测本机ipv6的小程序,本期就详细讲解一下实现过程,大家也可以在此基础上修改,达到自己的目的第一步导入需要用到的库import smtplibfrom email.m...【详细内容】
2022-10-03  迷之折腾  今日头条  Tags:python程序   点击:(19)  评论:(0)  加入收藏
今天给大家分享一波儿 Python学习重点,超级全面!由于总结了太多的东西,所以篇幅有点长,这也是“缝缝补补”总结了好久的东西。...【详细内容】
2022-09-30  联动企业实验室  搜狐号  Tags:Python   点击:(15)  评论:(0)  加入收藏
关键词:python 、 万花尺 、 turtle 、 fractions 模块 、 math 模块开发环境:PyCharm版本:python 3.9.5前言小时候我们使用设计工具,以落点为原点,沿外层工具大小画出不规则的图...【详细内容】
2022-09-30  老赖聊编程  今日头条  Tags:python   点击:(22)  评论:(0)  加入收藏
可读性的惊人 Python 代码片段 Python 是一种通用编程语言,可用于构建任何规模的项目,并为开发人员提供编写逻辑清晰代码的条件&mdash;&mdash;即使是大型项目。Python 的设计...【详细内容】
2022-09-26  喜欢编码的社畜  今日头条  Tags:Python   点击:(35)  评论:(0)  加入收藏
站内最新
站内热门
站内头条