Recommended popular and useful Python libraries

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've found that many of these modules contain functions that are very useful in a variety of areas. Comparing data sets, collaborating with other functions, and audio processing can all be automated using just Python.

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

grammar:

SequenceMatcher(None, string1, string2)

The following simple example shows what this function does:

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, which returns the closest match to the string passed in as an argument.

grammar:

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's 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 to this there are several other methods and classes belonging to Difflib that you can look at: unified_diff, Differ and diff_bytes

2. sched

sched is a useful module that centers on event scheduling for cross-platform work, in contrast to tools like Task Scheduler on Windows. Most of the time when using this module, you will use the scheduled class.

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

Create a schedule 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 are called in order. This function usually appears at the end of the program after the event has been scheduled.

enterabs() is a function that essentially adds events to the scheduler's internal queue. It receives several parameters in the following order:

  • event execution time
  • Activity priority
  • The event itself (a function)
  • Event function parameters
  • A dictionary of keyword arguments for the event

Here's 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. Binascii

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's 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 belonging to the binaascii module: a2b_qp(), b2a_qp(), and a2b_uu().

4. tty

tty is a module containing several utility functions for working with tty devices. The following 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.

A weak reference is a reference that does not protect a given object from being collected by the garbage collection mechanism.

The following are two functions related to this module:

  • getweakrefcount() accepts an object as a parameter and returns the number of weak references that refer to the object.
  • getweakrefs() takes an object and returns an array containing all weak references that refer to the object.

Examples of usage of weakref and its functions:

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

Output From the output function return value we can see what it does. Since num has no weak references, the array returned by getweakrefs() is empty.

Here are some other functions related to the weakref module: ref(), proxy(), and _remove_dead_weakref().

review

Difflib is a module for comparing data sets, especially strings . For example, a SequenceMatcher can compare two strings and return data based on their similarity.

sched is a useful tool used with the time module for scheduling events (in the form of functions) using a schedular instance. For example, enterabs() adds an event to the scheduler's internal queue, which will be run when the run() function is called.

binaascii converts between binary and ASCII to encode and decode data . b2a_base64 is a method in the binaascii module that converts base64 data to binary data.

The tty module needs to be used in conjunction with the 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.

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

[For those who want to learn Python by themselves, I have compiled a lot of Python learning materials and uploaded them to the CSDN official. Friends in need can scan the QR code below to obtain them]

1. Study Outline

Insert image description here

2. Development tools

Insert image description here

3. Python basic materials

Insert image description here

4. Practical data

Insert image description here

Guess you like

Origin blog.csdn.net/Z987421/article/details/132805194