


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.
1. Jpg to Png
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)
2. PDF encryption and decryption
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()
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 Brother J’s own computer as an example. You can see the configuration by running the code.
#4. Decompress the file
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")
5. Excel worksheet merging
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.
#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.
#The sketch is as follows, it’s quite nice.
#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.
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.
9. Screenshot
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")
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!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
