Table of Contents
Text
1. difflib
SequenceMatcher
get_close_matches
2. sched
3. binaascii
4. tty
5. weakref
回顾
要点
Home Backend Development Python Tutorial Do you know these five useful but little-known Python modules?

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

Apr 13, 2023 am 10:01 AM
python module

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

Syntax:

get_close_matches(word, possibilities, result_limit, min_similarity)
Copy after login

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']
Copy after login

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)
Copy after login

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
Copy after login

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'
Copy after login

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': []
Copy after login

输出从输出的函数返回值我们可以看到它的作用。由于 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 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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles