Thursday, 24 November 2022

Interesting 25 Python Packages

 

Introduction

Python community has evolved so much is the past few decades, today we will see some of the useful packages from PyPI - The Python Package Index. PyPI is the repository of the software for the python programming language.


Packages


1. Art

Module : art

Installation : pip install art

About:

    ASCII art is also known as "computer text art". It involves the smart placement of typed special characters or letters to make a visual shape that is spread over multiple lines of text.

    ART is a Python lib for text converting to ASCII art fancy. 

Sample:

from art import *

print("Coffee", art("coffee")) # return art as str in normal mode
print("")

print("Random", art("random")) # random 1-line art mode
print("")

print("Woman", art("woman",number=2)) # return multiple art as str
print("")

print("Butterfly")
aprint("butterfly") # print art
print("")

print("Happy")
aprint("happy") # print art
print("")

print("Text2Art")
print(text2art("art")) # Return ASCII text (default font) and default chr_ignore=True

Output:

Coffee c[_]

Random :-P

Woman ▓⚗_⚗▓ ▓⚗_⚗▓

Butterfly
Ƹ̵̡Ӝ̵̨̄Ʒ

Happy
ۜ\(סּںסּَ` )/ۜ

Text2Art
_
__ _ _ __ | |_
/ _` || '__|| __|
| (_| || | | |_
\__,_||_| \__|


Reference: https://pypi.org/project/art/


2. Beautiful

Module : BeautifulSoup

Installation : pip install BeautifulSoup

About:

    Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree.

Sample:

import requests
from bs4 import BeautifulSoup
URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)
# Note: If this line causes an error, run 'pip install html5lib' or install html5lib
soup = BeautifulSoup(r.content, 'html5lib') 

print(soup.prettify())

Reference: https://pypi.org/project/BeautifulSoup/


3. Bokeh

Module : bokeh

Installation : pip install bokeh

About:

    Bokeh is an interactive visualization library for modern web browsers. It provides elegant, concise construction of versatile graphics, and affords high-performance interactivity over large or streaming datasets. Bokeh can help anyone who would like to quickly and easily make interactive plots, dashboards, and data applications.

Sample:

import numpy as np

from bokeh.plotting import figure, show

N = 500
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)

p = figure(tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")])
p.x_range.range_padding = p.y_range.range_padding = 0

# must give a vector of image data for image parameter
p.image(image=[d], x=0, y=0, dw=10, dh=10,
palette="Spectral11", level="image")
p.grid.grid_line_width = 0.5

show(p)

Output:

Reference: https://pypi.org/project/bokeh/


4. Dis

Module: dis

Installation: pip install dis

About:

    The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.

Source Code:

import dis

def print_hello(string):
print("Hello", string)

# This will display the disassembly of print_hello
dis.dis(print_hello)

Output:

4 0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Hello')
4 LOAD_FAST 0 (string)
6 CALL_FUNCTION 2
8 POP_TOP
10 LOAD_CONST 0 (None)
12 RETURN_VALUE

Reference: https://pypi.org/project/dis/


5. Emoji

Module: emoji

Installation: pip install emoji

About: 

    Emoji for Python. The entire set of Emoji codes as defined by the unicode consortium is supported in addition to a bunch of aliases. By default, only the official list is enabled but doing emoji.emojize(language='alias') enables both the full list and aliases.

Sample:

import emoji
print(emoji.emojize('Python is :thumbs_up:'))
print(emoji.emojize('Python is :thumbsup:', language='alias'))
print(emoji.demojize('Python is 👍'))
print(emoji.emojize("Python is fun :red_heart:"))
print(emoji.emojize("Python is fun :red_heart:", variant="emoji_type"))
print(emoji.is_emoji("👍"))

Output:

Python is 👍
Python is 👍
Python is :thumbs_up:
Python is fun ❤️
Python is fun ❤️
True

Reference: https://pypi.org/project/emoji/


6. Faker

Module: Faker

Installation: pip install Faker

About: 

    Faker package helps to generate fake data, such as name, address, text, colour, date time, currencies, sentences, phone numbers and so on. To ensure that all the generated values are unique for specific funtion, the .unique method is called. Instead, to generate the same value each time, the seed() method is used.

Sample:

from faker import Faker
fake = Faker()

print("Name:", fake.name())
print("Address:", fake.address())
print("Email:", fake.email())
print("Phone Number:", fake.phone_number())
print("Company:", fake.company())
print("Text:", fake.text())

Output:

Name: Amy Odonnell
Address: 2984 Ortiz Stravenue
Lake Cynthia, LA 58335
Email: newtonbradley@gmail.com
Phone Number: (348)704-0954
Company: Weber-Carlson
Text: Response north speak yes five. Marriage under poor actually central. Send meet time great happy him future.
Analysis record half smile real rich. Partner for player social here.

Reference: https://pypi.org/project/Faker


7. Housie

Module : housie

Installation : pip install housie

About:

    As the festive season as begun, we would have lots of guests at home. Let's entertain them python way. Housie provides all the core models and logic required to simulate and play the classic game 'Housie' (also known as 'Bingo' or 'Tambola').

Execution:

python -m housie
Welcome to Housie!

Press 'N' to Host a New Game
Displays board, randomly picks numbers

Press 'T' to Generate Tickets
Generate tickets for Players to use to play the game

Press 'F' to Follow a Game
This mode allows you to follow a game being hosted by someone else, i.e. someone else is calling out the
numbers as you sit and mark your tickets. This mode automates the marking of your tickets and shows a nice
visual display of the board and your tickets. You can also quit and continue the game from where you left off
later. (Game state is persisted)

Before using this mode, enter your ticket(s) into 'data/followed_tickets.json' file in the current directory.
Then start this mode and keep entering the numbers being called out. The status of your ticket(s) are
automatically updated on screen.

(This mode saves files into the 'data' folder in order to store the
state of the housie board. If you want to start a new game, delete the file named 'data/followed_board.json')

Press 'Q' to Quit

Select an option to get started:

Reference: https://pypi.org/project/housie/


8. Mathematical

Module : mathematical

Installation : pip install mathematical

About:

    Includes tools for calculating mean, median and standard deviation of rows in data frames, detection of outliers, and statistical calculations

Sample:

from mathematical.outliers import quartile_outliers

data = [
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 10],
[1, 2, 3, 4, 50],
[1, 2, 3, 4, 100],
[1, 2, 3, 4, 1000],
[1, 2, 3, 50, 1000],
]

for d in data:
outliers, data_exc_outliers = quartile_outliers(d)
print("data: ", d)
print("outliers: ", outliers)
print("data leaving outliers: ", data_exc_outliers)
print("")

Output:

data: [1, 2, 3, 4, 5]
outliers: []
data leaving outliers: [1, 2, 3, 4, 5]


data: [1, 2, 3, 4, 10]
outliers: [10]
data leaving outliers: [1, 2, 3, 4]


data: [1, 2, 3, 4, 50]
outliers: [50]
data leaving outliers: [1, 2, 3, 4]


data: [1, 2, 3, 4, 100]
outliers: [100]
data leaving outliers: [1, 2, 3, 4]


data: [1, 2, 3, 4, 1000]
outliers: [1000]
data leaving outliers: [1, 2, 3, 4]


data: [1, 2, 3, 50, 1000]
outliers: [1000]
data leaving outliers: [1, 2, 3, 50]

Reference: https://pypi.org/project/mathematical/


9. Matplotlib

Module : matplotlib

Installation : pip install matplotlib

About:

    Matplotlib produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Source Code:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

plt.show()

Output:

Reference: https://pypi.org/project/matplotlib/


10. Moviepy

Module: moviepy

Installation: pip install moviepy

About: 

    MoviePy is a Python module for video editing, which can be used for basic operations (like cuts, concatenations, title insertions), video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write the most common video formats, including GIF.

Sample:

# Blurring all frames of a video
from skimage.filters import gaussian_filter
from moviepy.editor import VideoFileClip

def blur(image):
""" Returns a blurred (radius=2 pixels) version of the image """
return gaussian_filter(image.astype(float), sigma=2)

clip = VideoFileClip("my_video.mp4")
clip_blurred = clip.fl_image(blur)
clip_blurred.write_videofile("blurred_video.mp4")

Reference: https://pypi.org/project/moviepy/


11. NLTK

Module : nltk

Installation : pip install nltk

About:

    Natural Language Toolkit (NLTK) is one of the leading Python platforms for processing language data. It is a set of language processing libraries and programs that provide a toolkit for:

- Classification

- Tokenization

- Stemming

- Tagging

- Parsing

- Semantic reasoning

Sample:

import nltk
sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""

# Tokenization in NLP is the process by which a large quantity of text is divided into smaller parts called tokens.
tokens = nltk.word_tokenize(sentence)
tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

# POS Tagging in NLTK is a process to mark up the words in text format for a particular part of a speech based on its definition and context.
tagged = nltk.pos_tag(tokens)
tagged[0:6]
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]

Reference:

https://pypi.org/project/nltk/


12. Pendulum

Module: pendulum

Installation: pip install pendulum

About: 

    Library to work with dates and times. Handling and manipulating date, different zones, differences requires lots of attention and coding. Well today we have a module which would ease datetimes manipulation.

Sample Source Code:

import pendulum

# Current time in India
now_in_india = pendulum.now('Asia/Kolkata')
print("Current time in India: {}".format(now_in_india))

# Convert time in UTC timezone
print("Converted time in UTC timezone: {}".format(now_in_india.in_timezone('UTC')))

# Easy manipulations for with the dates
tomorrow = pendulum.now().add(days=1)
print("Tomorrow's date: {}".format(tomorrow))

last_week = pendulum.now().subtract(weeks=1)
print("Last Week same day date: {}".format(last_week))

past = pendulum.now().subtract(minutes=2)
print("Two mins's back time: {}".format(past))

print("Two mins's back time human readable: {}".format(past.diff_for_humans()))

delta = past - last_week
delta.hours
print("Time differences: {}".format(delta.hours))

Output:

"""
Current time in India: 2022-12-23T12:09:42.824254+05:30
Converted time in UTC timezone: 2022-12-23T06:39:42.824254+00:00
Tomorrow's date: 2022-12-24T12:09:42.827856+05:30
Last Week same day date: 2022-12-16T12:09:42.827989+05:30
Two mins's back time: 2022-12-23T12:07:42.828059+05:30
Two mins's back time human readable: 2 minutes ago
Time differences: 23
"""

Reference: https://pypi.org/project/pendulum/


13. Pillow

Module : Pillow

Installation : pip install Pillow

About:

    The Python Imaging Library adds image processing capabilities to Python interpreter. This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. The core image library is designed for fast access to data stored in a few basic pixel formats. It provides a solid foundation for a general image processing tool.

Source:

from PIL import Image
import PIL

# Location of the image
img = Image.open("image.jpeg")
# Show the image
img.show()

# Size of the image
weight, height = img.size
print(weight, height)
# Format of the image
print(img.format)

# Rotating a image 90 deg counter clockwise
img = img.rotate(90, PIL.Image.NEAREST, expand = 1)
# Flip the original image vertically
img = img.transpose(method=Image.FLIP_TOP_BOTTOM)


# Setting the points for cropped image
left = 4
top = height / 5
right = 154
bottom = 10 * height / 5
# Cropped image of the given dimension
img = img.crop((left, top, right, bottom))

# Resize the image
newsize = (300, 300)
img = img.resize(newsize)

# Show the image
img.show()

Input:

Output:

Reference: https://pypi.org/project/Pillow/


14. PrettyPinter

Module : prettyprinter

Installation : pip install prettyprinter

About:

    Write pretty printers for your standard type list, dict, etc and own types with a dead simple, declarative interface.

Sample:

from datetime import datetime
from prettyprinter import pprint, register_pretty, pretty_call

class MyClass:
def __init__(self, one, two):
self.one = one
self.two = two

@register_pretty(MyClass)
def pretty_myclass(value, ctx):
return pretty_call(ctx, MyClass, one=value.one, two=value.two)

## print the output of the date in pretty format
pprint({'beautiful output': datetime.now()})

## print class object in pretty format
pprint({'beautiful MyClass instance': MyClass((1, 2, 3), {'a': 1, 'b': 2})})

Output:

{
'beautiful output': datetime.datetime(
year=2022,
month=12,
day=23,
hour=12,
minute=29,
second=13,
microsecond=446417
)
}
{
'beautiful MyClass instance': MyClass(
one=(1, 2, 3),
two={'a': 1, 'b': 2}
)
}

Reference: https://pypi.org/project/prettyprinter/


15. Pycurl

Module : pycurl

Installation : pip install pycurl

About:

PycURL is a Python interface to libcurl, the multiprotocol FILE, FTPS, HTTP, HTTPS, IMAP, POP3, SMTP, SCP, SMB, etc. file transfer library. PycURL module can be used to fetch objects with high speed from a URL.

Sample:

import pycurl
from io import BytesIO

b_obj = BytesIO()
crl = pycurl.Curl()

# Set URL value
crl.setopt(crl.URL, 'https://wiki.python.org/moin/BeginnersGuide')

# Write bytes that are utf-8 encoded
crl.setopt(crl.WRITEDATA, b_obj)

# Perform a file transfer
crl.perform()

# End curl session
crl.close()

# Get the content stored in the BytesIO object (in byte characters)
get_body = b_obj.getvalue()

# Decode the bytes stored in get_body to HTML and print the result
print('Output of GET request:\n%s' % get_body.decode('utf8'))

Output:

Output of GET request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
.. < wiki page content > ..
</html>

Reference: https://pypi.org/project/pycurl/


16. Pygame

Module: pygame

Installation: pip install pygame

About:

    The pygame is a free and open-source cross-platform library for the development of multimedia applications like video games using Python.

Sample:

# Simple pygame program

# Import and initialize the pygame library
import pygame
pygame.init()

# Set up the drawing window
screen = pygame.display.set_mode([500, 500])

# Run until the user asks to quit
running = True
while running:

# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Fill the background with white
screen.fill((255, 255, 255))

# Draw a solid blue circle in the center
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)

# Flip the display
pygame.display.flip()

# Done! Time to quit.
pygame.quit()

Output:

Reference: https://pypi.org/project/pygame/


17. Pynguin

Module : pynguin

Installation : pip install pynguin

About:

    Pynguin, the PYthoN General UnIt test geNerator, is a tool that allows developers to generate unit tests automatically.

Sample Source Code:

def triangle(x: int, y: int, z: int) -> str:
if x == y == z:
return "Equilateral triangle"
elif x == y or y == z or x == z:
return "Isosceles triangle"
else:
return "Scalene triangle"

Prerequisite:

    To help prevent harming the system that runs Pynguin, its CLI will immediately abort unless the environment variable PYNGUIN_DANGER_AWARE is set.

% export PYNGUIN_DANGER_AWARE=1  

Execution:

% pynguin --project_path ./ --output-path pynguin_output --module-name pynguin_demo
% cd pynguin_output
pynguin_output % ls -rtl
total 16
-rw-r--r-- 1 dev staff 879 29 May 23:26 test_pynguin_demo.py
-rw-r--r-- 1 dev staff 38 29 May 23:26 test_pynguin_demo_failing.py

Output:

## Below testcase are automatically created by the module
# Automatically generated by Pynguin.
import pynguin_demo as module_0


def test_case_0():
int_0 = -156
int_1 = -5206
str_0 = module_0.triangle(int_1, int_0, int_1)
assert str_0 == 'Isosceles triangle'
str_1 = module_0.triangle(int_0, int_0, int_0)
assert str_1 == 'Equilateral triangle'

def test_case_1():
int_0 = 1038
int_1 = 5772
str_0 = module_0.triangle(int_0, int_1, int_1)
assert str_0 == 'Isosceles triangle'

def test_case_2():
int_0 = -785
int_1 = 3730
int_2 = -1030
str_0 = module_0.triangle(int_1, int_1, int_2)
assert str_0 == 'Isosceles triangle'
str_1 = module_0.triangle(int_0, int_0, int_0)
assert str_1 == 'Equilateral triangle'

def test_case_3():
int_0 = 1910
int_1 = 899
int_2 = None
str_0 = module_0.triangle(int_0, int_1, int_2)
assert str_0 == 'Scalene triangle'
Reference: https://pypi.org/project/pynguin/

18. Pyscreenshot

Module: pyscreenshot

Installation: pip install pyscreenshot

About: 

    Pyscreenshot tries to allow to take screenshots without installing 3rd party libraries. It is cross-platform.

Sample Source Code:

"Grab the whole screen"
import pyscreenshot as ImageGrab

# grab fullscreen
im = ImageGrab.grab()

# save image file
im.save("fullscreen.png")

Execution:

$ python pyscreenshot_sample.py

Output:

# screen shot will be created and saved in the fullscreen.png file
$ ls -lrt fullscreen.png

Reference: https://pypi.org/project/pyscreenshot/


19. Scrape

Module: scrape

Installation: pip install scrape

About: 

    Scrape is a rule-based web crawler and information extraction     tool capable of manipulating and merging new and existing documents. XML Path Language (XPath) and regular expressions are used to define rules for filtering content and web traversal. Output may be converted into text, csv, pdf, and/or HTML formats.

Sample:

from scrape import scrape, utils

def call_scrape(cmd, filetype, num_files=None):
if not isinstance(cmd, list):
cmd = [cmd]
parser = scrape.get_parser()
args = vars(parser.parse_args(cmd))

args["overwrite"] = True # Avoid overwrite prompt
if args["crawl"] or args["crawl_all"]:
args["no_images"] = True # Avoid save image prompt when crawling
args[filetype] = True
if num_files is not None:
args[num_files] = True
return scrape.scrape(args)

call_scrape(["demo.html"], "text")

Input: demo.html

<html><body>
ADMISSION TO ONLINE COLLEGE
<P>
Aplicants are considered for admission to Online College
on the basis of their ISP, quality of their home pages and
quantity of emails exchanged per day.
<P>
It is recommended that students prepare for enrollment in
Online College by signing up for DSL service and
buying a new computer.
<P>
<A HREF="home.html">Back to Online College home page</A> </body>
</HTML>

Execution:

$ python scrape_sample.py

Output: demo.txt

ADMISSION TO ONLINE COLLEGEAplicants are considered for admission to Online College on the basis of their ISP, quality of their home pages and quantity of emails exchanged per day.It is recommended that students prepare for enrollment in Online College by signing up for DSL service and buying a new computer.
Back to Online College home page

Reference: https://pypi.org/project/scrape/


20. Scrapy

Module : Scrapy

Installation : pip install Scrapy

About:

    Scrapy is a fast high-level web crawling and web scraping framework, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.

Sample:

import scrapy

class ToScrapeCSSSpider(scrapy.Spider):
name = "toscrape-css"
start_urls = [
'http://quotes.toscrape.com/',
]

def parse(self, response):
for quote in response.css("div.quote"):
yield {
'text': quote.css("span.text::text").extract_first(),
'author': quote.css("small.author::text").extract_first(),
'tags': quote.css("div.tags > a.tag::text").extract()
}

next_page_url = response.css("li.next > a::attr(href)").extract_first()
if next_page_url is not None:
yield scrapy.Request(response.urljoin(next_page_url))

Execution:

$ scrapy runspider scrape_sample.py -o quotes.json

Reference: https://pypi.org/project/Scrapy/


21. Tamilspellchecker

Module : tamilspellchecker

Installation : pip install tamilspellchecker

About:

    Tamil Spell Checker is used to suggest different spellings for a word. 

Source:

from tamilspellchecker.TamilSpellingAutoCorrect import TamilSpellingAutoCorrect, get_data
from pprint import pprint
from tamil.utf8 import get_letters

spellchecker = TamilSpellingAutoCorrect(get_data("tamil_bloom_filter.txt"), get_data("tamilwordlist.txt"))

###தமிழ்நாடு என்பது சரியான சொல்.
results = spellchecker.tamil_Norvig_correct_spelling("தமிழ்னாடு")

#filter for words >= 4 letters and for words <= 6 letters
results = list(filter(lambda x: len(get_letters(x)) >= 4,results ))
results = list(filter(lambda x: len(get_letters(x)) <= 6,results ))

pprint(results)

Output:

['தமிழ்கு',
'தமிழ்பு',
'தகை்னாடு',
'தமிழ்கொடு',
'தன்னாடு',
'தமிழ்ஏடு',
'தமிழ்நாடு',
'தமிழ்து',
'தமிணனாடு',
'தமிழ்பாடு',
'தமிழ்மு',
'தமிழ்விடு',
'தமினோோடு',
'தமிழ்கு',
'தமிழ்பு',
'தரீ்ஙோடு',
'தமிழ்கொடு',
'தமிழ்ஏடு',
'தமிழ்நாடு',
'தமிழோடு',
'தமிழ்து',
'தமிழ்பாடு',
'தமிழ்மு',
'தமிழ்விடு']

Reference: https://pypi.org/project/tamilspellchecker/


22. Thirukurral

Module : thirukkural

Installation : pip install thirukkural

About:

    A python3 module / command-line tool for Thirukkural.

Execution:

import thirukkural

print(thirukkural())

"""
# Display a random Thirukkural
% thirukkural

பால்: காமத்துப்பால்(3/3) | இயல்: களவியல்(9/10) | அதிகாரம்: தகையணங்குறுத்தல்(109/133)

குறள்-1085:
கூற்றமோ கண்ணோ பிணையோ மடவரல்
நோக்கமிம் மூன்றும் உடைத்து.

kootramoa kaNNoa piNaiyoa madavaral
noakkamim moondrum udaiththu

மு.வ உரை:
எமனோ. கண்ணோ, பெண்மானோ, இந்த இளம் பெண்ணின் பார்வை இந்த மூன்றன்
தன்மையும் உடையதாக இருக்கிறது.

சாலமன் பாப்பையா உரை:
என்னை துன்புறுத்துவது எமனா? என் மேனி எங்கும் படர்வதால் கண்ணா? ஏதோ ஒரு
பயம் தெரிவதால் பெண்மானா? இப்பெண்ணின் பார்வை இம்மூன்று குணங்களையும்
பெற்றிருக்கிறது.

# Display a random Thirukkural in English
% thirukkural -en

Category: Righteousness(1/3) | Sub-Category: Domestic Virtue(2/10) | Chapter: Duty to Society(22/133)

Verse-217:
Unfailing tree that healing balm distils from every part,
Is ample wealth that falls to him of large and noble heart.

Meaning:
If wealth be in the possession of a man who has the great excellence
(of benevolence), it is like a tree which as a medicine is an
infallible cure for disease.
"""

Reference: https://pypi.org/project/thirukkural/


23. Wikipedia

Module : wikipedia

Installation : pip install wikipedia

About:

    Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia.

    Search Wikipedia, get article summaries, get data like links and images from a page, and more. Wikipedia wraps the MediaWiki API so you can focus on using Wikipedia data, not getting it.

Sample:

import wikipedia
print("Wikipedia: ", wikipedia.summary("Wikipedia"))
print("Python: ", wikipedia.search("Python"))

wikipedia.set_lang("fr")
print("Threads: ", wikipedia.summary("Threads", sentences=1))

data = wikipedia.page("India")
print("India Title: ", data.title)
print("India URL: ", data.url)
print("India content: ", data.content)
print("India links: ", data.links[0])

Reference: https://pypi.org/project/wikipedia/


24. Zip Analyzer

Module : zip-analyzer

Installation : pip install zip-analyzer

About:

    A cli script to analyze zip archive.

Execution:

# zipAnalyzer --help
usage: zipAnalyzer FILE [OPTIONS]

A cli script to analyze zip archive.

optional arguments:
-h, --help show this help message and exit
-c, --crack tries to crack the encryption by enumeration over a password list. Extracts the zip archive if the password was found
--passlist PASSLIST Path to custom password list

# zipAnalyzer sample.zip
encrypted: False

File Name Modified Size
zip_analzer_notes.txt 2022-11-14 23:28:32 545

Reference: https://pypi.org/project/zip-analyzer/


25. Zoomlog

Module : zoomlog

Installation : pip install zoomlog

About:

        Simple python logger

Sample:

from zoomlog import Logger, DEBUG, INFO

logger = Logger("test.log", name="test", level=DEBUG)
logger.debug("My logger is work!")
name = "Sergey"
logger.addLevel("NEW USER", INFO)
logger.log("NEW USER", "Created new user - %s" % name)
Output:
10:45:20 25.12.22 DEBUG:test >> My logger is work!
10:45:20 25.12.22 NEW USER:test >> Created new user - Sergey
Reference: https://pypi.org/project/zoomlog/


Conclusion

Today thought to share with you few modules which I came across but a lot more. Sincerely appreciate the developers taken efforts to enrich the community! 


References and Credits

https://pypi.org

Scarcity Brings Efficiency: Python RAM Optimization

  In today’s world, with the abundance of RAM available, we rarely think about optimizing our code. But sooner or later, we hit the limits a...