search
HomeBackend DevelopmentPython TutorialFive useful Python modules you may not know about

你可能不知道的五个实用的 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)

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

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)

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']

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

2. sched

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

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

创建一个 ​schedular​ 实例:

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

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

  • 事件执行的时间
  • 活动优先级
  • 事件本身(一个函数)
  • 事件函数的参数
  • 事件的关键字参数字典
  • 调用 ​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

还有几个扩展 ​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'

该段代码应该是不言自明的。简单地说,它涉及编码、转换为 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': []

输出从输出的函数返回值我们可以看到它的作用。由于 ​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
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

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.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

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.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

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.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

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.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

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 vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

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.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

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 vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

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.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor