Home  >  Article  >  Backend Development  >  Share ten super practical Python automation scripts that get twice the result with half the effort

Share ten super practical Python automation scripts that get twice the result with half the effort

WBOY
WBOYforward
2023-04-12 16:31:151153browse

In our daily work and study, we always encounter various problems, many of which are simple and repeated operations over and over again. We might as well use Python scripts to automate processing. Today I will Let me share with you ten advanced Python scripts to help us reduce unnecessary waste of time and improve efficiency in work and study.

Share ten super practical Python automation scripts that get twice the result with half the effort

Add watermark to photos

There are various codes for adding watermark to photos. The following may be the simplest form:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

def watermark_Image(img_path,output_path, text, pos):
img = Image.open(img_path)
drawing = ImageDraw.Draw(img)
black = (10, 5, 12)
drawing.text(pos, text, fill=black)
img.show()
img.save(output_path)

img = '2.png'
watermark_Image(img, 'watermarked_2.jpg','Python爱好者集中营', pos=(10, 10))

Detecting similarity of text files

Many times we need to check the similarity of two files to see how much similarity there is. Maybe the following script file can Comes in handy:

from difflib import SequenceMatcher

def file_similarity_checker(f1, f2):
with open(f1, errors="ignore") as file1, open(f2, errors="ignore") as file2:
f1_data = file1.read()
f2_data = file2.read()
checking = SequenceMatcher(None, f1_data, f2_data).ratio()
print(f"These files are {checking*100} % similar")

file_1 = "路径1"
file_2 = "路径2"
file_similarity_checker(file_1, file_2)

Encrypt the file contentEncryption

Sometimes the content of the file in our hands is very is very important and very confidential. We can choose to encrypt it. The code is as follows:

from cryptography.fernet import Fernet

def encrypt(filename, key):
fernet = Fernet(key)
with open(filename, 'rb') as file:
original = file.read()
encrypted = fernet.encrypt(original)
with open(filename, 'wb') as enc_file:
enc_file.write(encrypted)

key = Fernet.generate_key()
filename = "file.txt"
encrypt(filename, key)

We generate a key and then encrypt the file content. Of course, this key is used to decrypt the file later. It will come in handy, so the key must be kept well. The decryption code is as follows:

def decrypt(filename, key):
fernet = Fernet(key)
with open(filename, 'rb') as enc_file:
encrypted = enc_file.read()
decrypted = fernet.decrypt(encrypted)
with open(filename, 'wb') as dec_file:
dec_file.write(decrypted)

decrypt(filename, key)

In the above script, the key is a randomly generated random number. Of course, the key can also be our own Specified, the code is as follows:

import pyAesCrypt

def Encryption(input_file_path, output_file_path, key):
pyAesCrypt.encryptFile(input_file_path, output_file_path, key)
print("File has been decrypted")

def Decryption(input_file_path, output_file_path, key):
pyAesCrypt.decryptFile(input_file_path, output_file_path, key)
print("File has been decrypted")

Convert photos to PDF

Sometimes we need to convert photos to PDF format, or add photos to PDF files in sequence, the code is as follows:

import os
import img2pdf

with open("Output.pdf", "wb") as file:
file.write(img2pdf.convert([i for i in os.listdir('文件路径') if i.endswith(".jpg")]))

Modify the length and width of the photo

If we want to modify the length and width of the photo, the following code can help. The code is as follows:

from PIL import Image
import os
def img_resize(file, h, w):
img = Image.open(file)
Resize = img.resize((h,w), Image.ANTIALIAS)
Resize.save('resized.jpg', 'JPEG', quality=90)

img_resize("文件路径", 400, 200)

For other operations on photos

In addition to modifying the length and width of the photo above, we also have other operations on the photo, such as blurring the content of the photo:

img = Image.open('1.jpg')
blur = img.filter(ImageFilter.BLUR)
blur.save('output.jpg')

Flip the photo 90 degrees:

img = Image.open('1.jpg')
rotate = img.rotate(90)
rotate.save('output.jpg')

To sharpen the photo:

img = Image.open('1.jpg')
sharp = img.filter(ImageFilter.SHARPEN)
sharp.save('output.jpg')

Flip the photo symmetrically to the left and right, the code is as follows:

img = Image.open('1.jpg')
transpose = img.transpose(Image.FLIP_LEFT_RIGHT)
transpose.save('output.jpg')

To process the photo in grayscale:

img = Image.open('1.jpg')
convert = img.convert('L')
convert.save('output.jpg')

Test Network speed

Of course we need to download the dependent modules in advance before starting to test the network speed

pip install speedtest-cli

Then we start to try to test the network speed:

from speedtest import Speedtest

def Testing_Speed(net):
download = net.download()
upload = net.upload()
print(f'下载速度: {download/(1024*1024)} Mbps')
print(f'上传速度: {upload/(1024*1024)} Mbps')
print("开始网速的测试 ...")

net = Speedtest()
Testing_Speed(net)

Currency exchange rate conversion

For example, we want to see the exchange rate conversion between US dollars and pounds, how many pounds can be converted from 100 US dollars, the code is as follows:

# 导入模块
from currency_converter import CurrencyConverter
from datetime import date
# 案例一
conv = CurrencyConverter()
c = conv.convert(100, 'USD', 'GBP')
print(round(c, 2)) # 保留两位小数

Or we want to see the exchange rate between US dollars and euros Exchange rate conversion between 100 U.S. dollars and how many euros can be converted into:

# 案例二
c = conv.convert(100, 'USD', 'EUR', date=date(2022, 3, 30))
print(round(c, 2)) # 44.1

Generate QR code

This includes the generation of QR code and the analysis of QR code. The code is as follows:

import qrcode
from PIL import Image
from pyzbar.pyzbar import decode

def Generate_qrcode(data):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,)
qr.add_data(data)
qr.make(fit=True)
image = qr.make_image(fill_color="black", back_color="white")
image.save("qrcode.png")

Generate_qrcode("Python爱好者集中营 欣一")

Let’s take a look at the analysis of the QR code. The code is as follows:

def Decode_Qrcode(file_name):
result = decode(Image.open(file_name))
print("Data:", result[0][0].decode())

Decode_Qrcode("文件名")

Make a simple web application

calls the flask module in Python to make a web application , the code is as follows:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
return "Hello World!"

@app.route("/python")
def test():
return "欢迎来到Python爱好者集中营,欣一"

if __name__ == "__main__":
app.run(debug=True)

The above is the detailed content of Share ten super practical Python automation scripts that get twice the result with half the effort. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete