Home >Backend Development >Python Tutorial >Ten interesting advanced Python scripts, recommended for collection!
Hello everyone, I am a rookie.
In our daily work, we always face various problems.
Many of these problems can be solved using some simple Python code. For example, not long ago, a 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 rookie brother 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.
Image format conversion. In the past, the first thing Brother J 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)
If you have 100 or more PDF files that need to be encrypted, do it manually Encryption is definitely not feasible and extremely time-consuming.
Using Python's pikepdf module, you can 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()
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 Brother J’s own computer as an example. You can see the configuration by running the code.
Use the zipfile module to decompress the file. In the same way, you can also compress the file.
# 解压文件 from zipfile import ZipFile unzip = ZipFile("file.zip", "r") unzip.extractall("output Folder")
helps you merge Excel worksheets into one table. The table contents are as follows.
#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.
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.
#The sketch is as follows, it’s quite nice.
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)
Sometimes, we need to extract table data from PDF.
You may first 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 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.
#The contents of the extracted CSV file are as follows.
This script will simply take a screenshot without using any screenshot software.
In the following code, 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")
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!