Home > Backend Development > Python Tutorial > Five useful Python modules you may not know about

Five useful Python modules you may not know about

WBOY
Release: 2023-05-14 17:01:06
forward
1666 people have browsed it

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

Related labels:
source:51cto.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template