Home  >  Article  >  Backend Development  >  Do you know these five useful but little-known Python modules?

Do you know these five useful but little-known Python modules?

王林
王林forward
2023-04-13 10:01:051164browse

Do you know these five useful but little-known Python modules?

Text

The Python standard library has more than 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. This article contains several lesser-known functions and classes, so even if you have heard of these modules, you may not know some of their aspects and uses.

1. difflib

difflib is a Python module focused on comparing data sets (especially strings). 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 function that compares two strings and returns data based on their similarity. By using ratio() we will be able to quantify this similarity in terms of 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 argument.

Syntax:

get_close_matches(word, possibilities, result_limit, min_similarity)

Here’s an explanation of these potentially confusing parameters:

  • 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).

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

In addition there are several other methods that belong to Difflib that you can check out and Classes: unified_diff, Differ, and diff_bytes

2. sched

sched is a useful module centered around event scheduling that works cross-platform, in conjunction with tools such as the task scheduler on Windows sharp contrast. Most of the time when using this module, you will use the schedular class.

The more common time module is usually used together with sched because they both deal with the concepts of time and scheduling.

Create a schedular instance:

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

Various methods can be called from this instance.

  • When run() is called, the events/entries in the scheduler will be called in order. This function usually appears at the end of the program after the event has been scheduled. In addition, search the public account Linux to learn how to reply "git books" in the background and get a surprise gift package.
  • enterabs() is a function that essentially adds events to the scheduler's internal queue. It receives several parameters in the following order:
  • The time when the event is executed
  • The priority of the activity
  • The event itself (a function)
  • Parameters of the event function
  • Dictionary of keyword parameters for the event

Here is an example of how to use these two functions together:

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

There are also several functions that extend the use of the sched module: cancel(), enter() and empty().

3. binaascii

binaascii is a module for converting between binary and ASCII.

b2a_base64 is a method in the binaascii module that converts base64 data to binary data. Here is an example of this approach:

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'

This code should be self-explanatory. Simply put, it involves encoding, converting to base64, and converting it back to binary using the b2a_base64 method.

Here are some other functions that belong to the binaascii module: a2b_qp(), b2a_qp(), and a2b_uu().

4. tty

tty is a module containing several utility functions that can be used to deal with tty devices. Here are its two functions:

  • setraw() changes the mode of the file descriptor in its argument (fd) to raw.
  • setcbreak() changes the mode of the file descriptor in its argument (fd) to cbreak.

This module is only available on Unix due to the need to use the termios module, such as specifying the second parameter (when=termios.TCSAFLUSH) in the above two functions.

5. weakref

weakref is a module for creating weak references to objects in Python.

Weak references are references that do not protect a given object from being collected by the garbage collection mechanism.

The following are two functions related to this module:

  • 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()。

回顾

  • Difflib 是一个用于比较数据集,尤其是字符串的模块。例如,SequenceMatcher 可以比较两个字符串并根据它们的相似性返回数据。
  • sched 是与 time 模块一起使用的有用工具,用于使用 schedular 实例安排事件(以函数的形式)。例如,enterabs() 将一个事件添加到调度程序的内部队列中,该队列将在调用 run() 函数时运行。

binaascii 可在二进制和 ASCII 之间转换以编码和解码数据。b2a_base64 是 binaascii 模块中的一种方法,它将 base64 数据转换为二进制数据。

tty 模块需要配合使用 termios 模块,并处理 tty 设备。它仅适用于 Unix。

weakref 用于弱引用。它的函数可以返回对象的弱引用,查找对象的弱引用数量等。其中非常使用的函数之一是 getweakrefs(),它接受一个对象并返回一个该对象包含的所有弱引用的数组。

要点

这些函数中的每一个都有其各自的用途,每一个都有不同程度的有用性。了解尽可能多的 Python 函数和模块非常重要,以便保持稳定的工具库,您可以在编写代码时快速使用。

无论您的编程专业知识水平如何,您都应该不断学习。多投入一点时间可以为您带来更多价值,并为您节省更多未来时间。

The above is the detailed content of Do you know these five useful but little-known Python modules?. 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