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

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

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.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

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.

See all articles