Home  >  Article  >  Backend Development  >  Ten interesting advanced Python scripts, recommended for collection!

Ten interesting advanced Python scripts, recommended for collection!

王林
王林forward
2023-04-14 20:46:012261browse

Ten interesting advanced Python scripts, recommended for collection!

In our daily work, we will always face various problems.

Many of these problems can be solved using some simple Python code.

For example, not long ago, a big boss from Fudan University used 130 lines of Python code to solve nucleic acid statistics, which greatly improved efficiency and saved a lot of time.

Today, Xiao F will teach you 10 Python script programs.

Although simple, it is still quite useful.

Those who are interested can implement it themselves and find techniques that will help them.

1. Jpg to Png

Image format conversion. In the past, the first thing Xiao F might have thought of was the software [Format Factory].

Nowadays, writing a Python script can complete the conversion of various image formats. Here, we take the conversion of jpg to png as an example.

There are two solutions, both shared with everyone.

# 图片格式转换, Jpg转Png
# 方法①
from PIL import Image
img = Image.open('test.jpg')
img.save('test1.png')
# 方法②
from cv2 import imread, imwrite
image = imread("test.jpg", 1)
imwrite("test2.png", image)

2. PDF encryption and decryption

If you have 100 or more PDF files that need to be encrypted, manually encrypting them is definitely not feasible and is extremely time-consuming.

Use Python's pikepdf module to encrypt files, and write a loop to encrypt documents in batches.

# PDF加密
import pikepdf
pdf = pikepdf.open("test.pdf")
pdf.save('encrypt.pdf', encryption=pikepdf.Encryption(owner="your_password", user="your_password", R=4))
pdf.close()

If there is encryption, there will be decryption. The code is as follows.

# PDF解密
import pikepdf
pdf = pikepdf.open("encrypt.pdf",password='your_password')
pdf.save("decrypt.pdf")
pdf.close()

3. Obtain computer configuration information

Many friends may use Master Lu to view their computer configuration, which requires downloading a software.

Using Python's WMI module, you can easily view your computer information.

# 获取计算机信息
import wmi
def System_spec():
Pc = wmi.WMI()
os_info = Pc.Win32_OperatingSystem()[0]
processor = Pc.Win32_Processor()[0]
Gpu = Pc.Win32_VideoController()[0]
os_name = os_info.Name.encode('utf-8').split(b'|')[0]
ram = float(os_info.TotalVisibleMemorySize) / 1048576
print(f'操作系统: {os_name}')
print(f'CPU: {processor.Name}')
print(f'内存: {ram} GB')

print(f'显卡: {Gpu.Name}')
print("n计算机信息如上 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑")
System_spec()

Take Xiao F’s own computer as an example. You can see the configuration by running the code.

Ten interesting advanced Python scripts, recommended for collection!

4. Decompress files

Use the zipfile module to decompress files. In the same way, files can also be compressed.

# 解压文件
from zipfile import ZipFile
unzip = ZipFile("file.zip", "r")
unzip.extractall("output Folder")

5. Excel worksheet merging

helps you merge Excel worksheets into one table. The table content is as shown below.

Ten interesting advanced Python scripts, recommended for collection!

#6 tables, the contents of the remaining tables are the same as the first table.

Set the number of tables to 5, and the contents of the first 5 tables will be merged.

import pandas as pd
# 文件名
filename = "test.xlsx"
# 表格数量
T_sheets = 5
df = []
for i in range(1, T_sheets+1):
sheet_data = pd.read_excel(filename, sheet_name=i, header=None)
df.append(sheet_data)
# 合并表格
output = "merged.xlsx"
df = pd.concat(df)
df.to_excel(output)

The results are as follows.

Ten interesting advanced Python scripts, recommended for collection!

6. Convert the image to a sketch

is somewhat similar to the previous image format conversion, which is to process the image.

In the past, you might have used Meitu Xiuxiu, but now it might be Douyin’s filters.

In fact, using Python’s OpenCV, you can quickly achieve many of the effects you want.

# 图像转换
import cv2
# 读取图片
img = cv2.imread("img.jpg")
# 灰度
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey)
# 高斯滤波
blur_img = cv2.GaussianBlur(invert, (7, 7), 0)
inverse_blur = cv2.bitwise_not(blur_img)
sketch_img = cv2.divide(grey, inverse_blur, scale=256.0)
# 保存
cv2.imwrite('sketch.jpg', sketch_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The original picture is as follows.

Ten interesting advanced Python scripts, recommended for collection!

The sketch is as follows, it’s quite nice.

Ten interesting advanced Python scripts, recommended for collection!

7. Get the CPU temperature

With this Python script, you won’t need any software to know the CPU temperature.

# 获取CPU温度
from time import sleep
from pyspectator.processor import Cpu
cpu = Cpu(monitoring_latency=1)
with cpu:
while True:
print(f'Temp: {cpu.temperature} °C')
sleep(2)

8. Extract PDF tables

Sometimes, we need to extract table data from PDF.

For a while, you may first think of manual finishing, but when the workload is particularly heavy, manual work may be more laborious.

Then you may think of some software and online tools to extract PDF tables.

The simple script below will help you accomplish the same operation in just a second.

# 方法①
import camelot
tables = camelot.read_pdf("tables.pdf")
print(tables)
tables.export("extracted.csv", f="csv", compress=True)
# 方法②, 需要安装Java8
import tabula
tabula.read_pdf("tables.pdf", pages="all")
tabula.convert_into("table.pdf", "output.csv", output_format="csv", pages="all")

The content of the PDF document is as follows, including a table.

Ten interesting advanced Python scripts, recommended for collection!

The contents of the extracted CSV file are as follows.

Ten interesting advanced Python scripts, recommended for collection!

9. Screenshot

This script will simply take a screenshot without using any screenshot software.

In the code below, we show you two methods of taking screenshots in Python.

# 方法①
from mss import mss
with mss() as screenshot:
screenshot.shot(output='scr.png')
# 方法②
import PIL.ImageGrab
scr = PIL.ImageGrab.grab()
scr.save("scr.png")

10. Spell checker

This Python script can perform spell check. Of course, it is only valid for English. After all, Chinese is broad and profound.

# 拼写检查
# 方法①
import textblob
text = "mussage"
print("original text: " + str(text))
checked = textblob.TextBlob(text)
print("corrected text: " + str(checked.correct()))
# 方法②
import autocorrect
spell = autocorrect.Speller(lang='en')
# 以英语为例
print(spell('cmputr'))
print(spell('watr'))
print(spell('survice'))

The above is the detailed content of Ten interesting advanced Python scripts, recommended for collection!. 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