Python can be used in many directions, such as crawlers, predictive analysis, GUI, automation, image processing, visualization, etc. It may only take a dozen lines of code to achieve cool functions.
Because Python is a dynamic scripting language, the code logic is much simpler than Java, and a lot less code is needed to achieve the same function. Moreover, the Python ecosystem has many third-party tool libraries that encapsulate functions in packages. You only need to call the interface to use complex functions.
Here are a few simple and fun script examples. Beginners can follow the code and quickly master python syntax.
1. Use PIL, Matplotlib, and Numpy to repair blurry old photos
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) img = np.asarray(img) flat = img.flatten() def get_histogram(image, bins): histogram = np.zeros(bins) for pixel in image: histogram[pixel] += 1 return histogram hist = get_histogram(flat, 256) cs = np.cumsum(hist) nj = (cs - cs.min()) * 255 N = cs.max() - cs.min() cs = nj / N cs = cs.astype('uint8') img_new = cs[flat] img_new = np.reshape(img_new, img.shape) fig = plt.figure() fig.set_figheight(15) fig.set_figwidth(15) fig.add_subplot(1, 2, 1) plt.imshow(img, cmap='gray') plt.title("Image 'Before' Contrast Adjustment") 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.show()
2. Compress files in batches and use the zipfile library
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. Use tkinter to make a calculator GUI
tkinter is python’s own GUI library, suitable for beginners to practice creating small software
import tkinter as tk root = tk.Tk() root.title("Standard Calculator") root.resizable(0, 0) 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): temp = e.get( ) e.delete(0, tk.END) e.insert(0, temp + num) def buttonClear(): e.delete(0, tk.END)
4. Convert PDF to Word file
Use the pdf2docx library to convert PDF files to Word format
from pdf2docx import Converter import os import sys pdf = input("Enter the path to your file: ") assert os.path.exists(pdf), "File not found at, "+str(pdf) f = open(pdf,'r+') 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'): doc_name = input("Enter the custom name : ")+".docx" else: pdf_name = os.path.basename(pdf) doc_name =os.path.splitext(pdf_name)[0] + ".docx" cv = Converter(pdf) 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 automatically sends emails
This can be achieved using smtplib and email libraries Script sends 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 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 = """你好,这是一个测试邮件!""" message_text = MIMEText(body_content,"plain","utf-8") 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) stp = smtplib.SMTP() stp.connect(mail_host, 25) stp.set_debuglevel(1) stp.login(mail_sender,mail_license) stp.sendmail(mail_sender, mail_receivers, mm.as_string()) print("邮件发送成功") stp.quit()
Summary
Python also has many fun little scripts. You can write them according to your own scenarios, or you can use Ready-made third-party libraries.
The above is the detailed content of Five interesting Python scripts. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.