Five useful Python modules you may not know about
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)
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 a parameter.
Grammar:
get_close_matches(word, possibilities, result_limit, min_similarity)
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']
除此之外还有几个是您可以查看的属于 Difflib
的其他一些方法和类:unified_diff
、Differ
和 diff_bytes
2. sched
sched
是一个有用的模块,它以跨平台工作的事件调度为中心,与 Windows 上的任务调度程序等工具形成鲜明对比。大多数情况下,使用此模块时,都会使用 schedular
类。
更常见的 time
模块通常与 sched
一起使用,因为它们都处理时间和调度的概念。
创建一个 schedular
实例:
schedular_name = sched.schedular(time.time, time.sleep)
可以从这个实例中调用各种方法。
- 事件执行的时间
- 活动优先级
- 事件本身(一个函数)
- 事件函数的参数
- 事件的关键字参数字典
- 调用
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
还有几个扩展 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'
该段代码应该是不言自明的。简单地说,它涉及编码、转换为 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': []
输出从输出的函数返回值我们可以看到它的作用。由于 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 thetime
module for useschedular
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 whenrun()
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











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.

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.

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

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

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.
