Table of Contents
1. difflib
2. sched
3. binaascii
4. tty
5. weakref
Review
Key Points
Home Backend Development Python Tutorial Five useful Python modules you may not know about

Five useful Python modules you may not know about

May 14, 2023 pm 05:01 PM
python programming language

你可能不知道的五个实用的 Python 模块

The Python standard library has over 200 modules that programmers can import and use in their programs. While the average programmer will have some experience with many of these modules, it's likely that there are some useful ones that they're still unaware of.

I found that many of these modules contain functions that are very useful in various fields. Comparing data sets, collaborating with other functions, and audio processing can all be automated using just Python.

So, I have compiled a shortlist of Python modules that you may not know about and have given a proper explanation of these few modules so that you can understand and use them in the future.

All these modules have different functions and classes. I've included several lesser-known functions and classes, so even if you've heard of these modules, you may not know some of their aspects and uses.

1. difflib

​difflib​ is a tool that focuses on comparing data sets (especially strings ) Python module. To get a concrete idea of ​​a few things you can do with this module, let's examine some of its most common functions.

SequenceMatcher

​SequenceMatcher​ is a method that compares two strings and returns them based on their similarity function of the data. By using ​ratio()​​, we will be able to quantifythis similarity in terms of a ratio/percentage .

Syntax:

SequenceMatcher(None, string1, string2)

Copy after login

The following simple example shows the function of this function:

from difflib import SequenceMatcher

phrase1 = "Tandrew loves Trees."
phrase2 = "Tandrew loves to mount Trees."
similarity = SequenceMatcher(None, phrase1, phrase2)
print(similarity.ratio())
# Output: 0.8163265306122449

Copy after login

get_close_matches

Next Is ​get_close_matches​​, this function returns the closest match to the string passed in as a parameter.

Grammar:

get_close_matches(word, possibilities, result_limit, min_similarity)

Copy after login

Let’s explain these parameters that may be confusing:

  • ​word​ is the target word that the function will look at.
  • ​possibilities​ is an array containing the matches that the function will look for and find the closest match.
  • ​result_limit​ is the limit on the number of results returned (optional).
  • ​min_similarity​ is the minimum similarity that two words need to have in order to be considered a return value by the function (optional).

The following is an example of its use:

from difflib import get_close_matches

word = 'Tandrew'
possibilities = ['Andrew', 'Teresa', 'Kairu', 'Janderson', 'Drew']

print(get_close_matches(word, possibilities))
# Output: ['Andrew']

Copy after login

除此之外还有几个是您可以查看的属于 ​Difflib​ 的其他一些方法和类:​​unified_diff​​、​​Differ​ ​diff_bytes​

2. sched

​sched​ 是一个有用的模块,它以跨平台工作的事件调度为中心,与 Windows 上的任务调度程序等工具形成鲜明对比。大多数情况下,使用此模块时,都会使用 ​schedular​ 类。

更常见的 ​time​ 模块通常与 ​sched​ 一起使用,因为它们都处理时间和调度的概念。

创建一个 ​schedular​ 实例:

schedular_name = sched.schedular(time.time, time.sleep)

Copy after login

可以从这个实例中调用各种方法。

  • 事件执行的时间
  • 活动优先级
  • 事件本身(一个函数)
  • 事件函数的参数
  • 事件的关键字参数字典
  • 调用 ​run()​ 时,调度程序中的事件/条目会按照顺序被调用。在安排完事件后,此函数通常出现在程序的最后。
  • ​enterabs()​ 是一个函数,它本质上将事件添加到调度程序的内部队列中。它按以下顺序接收几个参数:

下面是一个示例,说明如何一起使用这两个函数:

import sched
import time


def event_notification(event_name):
    print(event_name + " has started")


my_schedular = sched.scheduler(time.time, time.sleep)
closing_ceremony = my_schedular.enterabs(time.time(), 1, event_notification, ("The Closing Ceremony", ))

my_schedular.run()
# Output: The Closing Ceremony has started

Copy after login

还有几个扩展 ​sched​ 模块用途的函数:​​cancel()​​、​​enter()​ ​empty()​​。

3. binaascii

​binaascii​ 是一个用于在二进制和 ASCII 之间转换的模块。

​b2a_base64​ ​binaascii​ 模块中的一种方法,它将 base64 数据转换为二进制数据。下面是这个方法的一个例子:

import base64
import binascii

msg = "Tandrew"
encoded = msg.encode('ascii')
base64_msg = base64.b64encode(encoded)
decode = binascii.a2b_base64(base64_msg)
print(decode)
# Output: b'Tandrew'

Copy after login

该段代码应该是不言自明的。简单地说,它涉及编码、转换为 base64,以及使用 ​b2a_base64​ 方法将其转换回二进制。

以下是属于 ​binaascii​ 模块的其他一些函数:​​a2b_qp()​​、​​b2a_qp()​ ​a2b_uu()​​。

4. tty

​tty​ 是一个包含多个实用函数的模块,可用于处理 ​tty​ 设备。以下是它的两个函数:

  • setraw() 将其参数 (fd) 中文件描述符的模式更改为 raw。
  • setcbreak() 将其参数 (fd) 中的文件描述符的模式更改为 cbreak。

由于需要使用 ​termios​ 模块,该模块仅适用于 Unix,例如在上述两个函数中指定第二个参数(​​when=termios.TCSAFLUSH​​)。

5. weakref

​weakref​ 是一个用于在 Python 中创建对对象的弱引用的模块。

弱引用是不保护给定对象不被垃圾回收机制收集的引用。

以下是与该模块相关的两个函数:

  • getweakrefcount() 接受一个对象作为参数,并返回引用该对象的弱引用的数量。
  • getweakrefs() 接受一个对象并返回一个数组,其中包含引用该对象的所有弱引用。

​weakref​ 及其函数的使用示例:

import weakref


class Book:
    def print_type(self):
        print("Book")


lotr = Book
num = 1
rcount_lotr = str(weakref.getweakrefcount(lotr))
rcount_num = str(weakref.getweakrefcount(num))
rlist_lotr = str(weakref.getweakrefs(lotr))
rlist_num = str(weakref.getweakrefs(num))

print("number of weakrefs of 'lotr': " + rcount_lotr)
print("number of weakrefs of 'num': " + rcount_num)

print("Weakrefs of 'lotr': " + rlist_lotr)
print("Weakrefs of 'num': " + rlist_num)
# Output: 
# number of weakrefs of 'lotr': 1
# number of weakrefs of 'num': 0
# Weakrefs of 'lotr': [<weakref at 0x10b978a90; to 'type' at #0x7fb7755069f0 (Book)>]
# Weakrefs of 'num': []

Copy after login

输出从输出的函数返回值我们可以看到它的作用。由于 ​num​ 没有弱引用,因此 ​getweakrefs()​ 返回的数组为空。

以下是与 ​weakref​ 模块相关的一些其他函数:​​ref()​​、​​proxy()​  ​_remove_dead_weakref()​​。

Review

  • Difflib is a module for comparing data sets, especially strings. For example, SequenceMatcher can compare two strings and return data based on their similarity.
  • sched is a useful tool for use with the time module for use schedular Instance schedules events (in the form of a function). For example, enterabs() adds an event to the scheduler's internal queue, which will be called when run() Run when the function is executed.

​binaascii​ Converts between binary and ASCII to encode and decode data. ​​b2a_base64​ is a method in the ​binaascii​ module, which will Convert base64 data to binary data.

​tty​ Modules need to be used together ​termios​ module, and handles tty devices. It only works on Unix.

​weakref​ is used for weak references. Its functions can return weak references to an object, find the number of weak references to an object, etc. One of the most commonly used functions is ​getweakrefs()​​, which takes an object and returns an array of all weak references contained in the object.

Key Points

Each of these functions has its own purpose, and each has varying degrees of usefulness. It's important to know as many Python functions and modules as possible in order to maintain a stable library of tools that you can use quickly when writing code.

No matter your level of programming expertise, you should always be learning. Investing a little more time can bring you more value and save you more time in the future.

The above is the detailed content of Five useful Python modules you may not know about. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles