


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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment