10 interesting practical Python scripts, recommended for collection!

In our daily work, we always face various problems.
Many of these problems can be solved using some simple Python code. For example, the former Fudan boss used 130 lines of Python code to complete nucleic acid statistics, which greatly improved efficiency and saved a lot of time. Today, the editor will take you to learn 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. Convert Jpg to Png

For image format conversion, in the past, Xiao F might have thought of the software [Format Factory] first. 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, then 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 check 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()

4. Unzip the file

Use the zipfile module to decompress files and compress files in the same way.

# 解压文件
from zipfile import ZipFile

unzip = ZipFile("file.zip", "r")
unzip.extractall("output Folder")

5. Merge Excel worksheets

Helps you merge Excel worksheets into one table. The table content is as shown below.
Insert image description here
There are 6 tables, and the contents of the remaining tables are the same as the first table.

Setting the number of tables to 5 will merge the contents of the first five tables.

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 result is as follows:
Insert image description here

6. Convert image to sketch

It 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.
Insert image description here
The sketch is as follows, it’s quite nice.Insert image description here

7. Get the CPU temperature

With this Python script, you won't need any software to know your CPU's 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 forms

Sometimes, we need to extract tabular data from PDF.

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

Then you might think of some software and web tools to extract PDF tables.

The simple script below will help you accomplish the same 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.
Insert image description here

The contents of the extracted CSV file are as follows.

Insert image description here

9. Screenshot

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

In the code below, I 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 checking, but of course it only works in 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'))

Guess you like

Origin blog.csdn.net/Everly_/article/details/133267933
Recommended