


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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools