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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

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

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

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.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

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.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

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

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

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: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

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.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

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

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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft