Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday 16 April 2024

Element information using Python

 

Code:

import periodictable


# Function to get information about an element

def get_element_info(symbol):

    # Check if the symbol is valid

    if not periodictable.elements.symbol(symbol):

        print("Invalid element symbol.")

        return    

    # Access information about the specified element

    element = periodictable.elements.symbol(symbol)

    

    # Print information about the element

    print(f"Element: {element.name}")

    print(f"Symbol: {element.symbol}")

    print(f"Atomic Number: {element.number}")

    print(f"Atomic Weight: {element.mass}")

    print(f"Density: {element.density}")

    

# Prompt the user to input an element symbol

element_symbol = input("Enter the symbol of the element: ")


# Call the function to get information about the specified element

get_element_info(element_symbol)


#clcoding.com

Explanation:

The line import periodictable imports a Python library/module named "periodictable". This library provides information about chemical elements such as their names, symbols, atomic numbers, atomic weights, and other properties.

In the provided code:

get_element_info(symbol) is a function that takes an element symbol as input and retrieves information about that element.
if not periodictable.elements.symbol(symbol): checks if the symbol entered by the user is valid. If it's not valid, it prints "Invalid element symbol." and exits the function.
element = periodictable.elements.symbol(symbol) accesses the information about the specified element using the symbol() method provided by the periodictable library.
Information about the element, such as its name, symbol, atomic number, atomic weight, and density (if available), is then printed using print statements.
The code prompts the user to input an element symbol, then calls the get_element_info function to display information about the specified element. If the element symbol provided by the user is not valid, it informs the user about the invalid input.

Monday 15 April 2024

Automatically Generate Image CAPTCHAs with Python for Enhanced Security

 

Code:

from captcha.image import ImageCaptcha 

import random

# Specify the image size

image = ImageCaptcha(width=450, height=100)

# Generate random captcha text

def generate_random_captcha_text(length=6):

    characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    captcha_text = ''.join(random.choice(characters) for _ in range(length))

    return captcha_text


# Get random captcha text

captcha_text = generate_random_captcha_text()


# Generate the image of the given text

data = image.generate(captcha_text)


# Write the image on the given file and save it

image.write(captcha_text, 'CAPTCHA1.png')


from PIL import Image

Image.open('CAPTCHA1.png')


#clcoding.com


Explanation: 

This code snippet demonstrates how to automatically generate an image CAPTCHA using Python. Here's a breakdown of each part:

from captcha.image import ImageCaptcha: This imports the ImageCaptcha class from the captcha.image module. This class allows you to create CAPTCHA images.

import random: This imports the random module, which is used to generate random characters for the CAPTCHA text.

image = ImageCaptcha(width=450, height=100): This initializes an instance of the ImageCaptcha class with the specified width and height for the CAPTCHA image.

generate_random_captcha_text(length=6): This is a function that generates random CAPTCHA text. It takes an optional parameter length, which specifies the length of the CAPTCHA text. By default, it generates a text of length 6.

captcha_text = generate_random_captcha_text(): This calls the generate_random_captcha_text function to generate random CAPTCHA text and assigns it to the variable captcha_text.

data = image.generate(captcha_text): This generates the CAPTCHA image using the generated text. It returns the image data.

image.write(captcha_text, 'CAPTCHA1.png'): This writes the generated CAPTCHA image to a file named "CAPTCHA1.png" with the text embedded in the image.

from PIL import Image: This imports the Image class from the Python Imaging Library (PIL) module, which is used to open and display the generated CAPTCHA image.

Image.open('CAPTCHA1.png'): This opens the generated CAPTCHA image named "CAPTCHA1.png" using the PIL library.

Overall, this code generates a random CAPTCHA text, creates an image of the text using the ImageCaptcha class, saves the image to a file, and then displays the image using PIL.

Saturday 13 April 2024

Remove Image Background using Python

 

from rembg import remove

from PIL import Image

input_path = 'p22.jpg'

output_path = 'p22.png'

inp = Image.open(input_path)

output = remove(inp)

output.save(output_path)

#clcoding.com

Explanantion: 

This code snippet appears to be a Python script using the rembg library to remove the background from an image. Let me break it down for you:

from rembg import remove: This line imports the remove function from the rembg library. rembg is likely a library designed for background removal from images.

from PIL import Image: This line imports the Image module from the Python Imaging Library (PIL). PIL is used for opening, manipulating, and saving many different image file formats.

input_path = 'p22.jpg': This line sets the path to the input image file named "p22.jpg". This is the image from which we want to remove the background.

output_path = 'p22.png': This line sets the path for the output image file named "p22.png". The background-removed image will be saved with this filename and format (PNG).

inp = Image.open(input_path): This line opens the input image file using PIL's Image.open() function and assigns it to the variable inp. Now inp holds the image object.

output = remove(inp): This line calls the remove() function from the rembg library and passes the input image (inp) as an argument. This function is expected to perform the background removal operation on the input image.

output.save(output_path): This line saves the background-removed image (output) to the specified output path (output_path). It's saved in PNG format due to the extension provided in the output_path.

The comments at the end (#clcoding.com) seem to indicate the source or reference of the code, possibly a website or a tutorial where this code was found.






Python library to filter and censor offensive language

 

from better_profanity import profanity

text = "What the hell is going on?"

censored_text = profanity.censor(text)

print(censored_text)  


#clcoding.com

Explanation: 

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and censoring offensive language in text.

Here's a breakdown of the subsequent code:

text = "What the hell is going on?": This line assigns a string containing a sentence to the variable text. The sentence includes the word "hell," which is considered offensive.

censored_text = profanity.censor(text): This line uses the censor function from the profanity module to censor any profanity in the text variable. The function replaces offensive words with asterisks (*) or other censor characters.

print(censored_text): This line prints the censored version of the text to the console. In this case, since "hell" is considered offensive, it will be replaced with asterisks, resulting in a censored version of the original sentence.

So, the output of this code will be a censored version of the original text, where the offensive word "hell" is replaced with asterisks.


from better_profanity import profanity

text = "I can't believe he said that!"

has_profanity = profanity.contains_profanity(text)

print(has_profanity) 


#clcoding.com

Explanation:

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and detecting offensive language in text.

Here's a breakdown of the subsequent code:

text = "I can't believe he said that!": This line assigns a string containing a sentence to the variable text. The sentence does not contain any explicit profanity.

has_profanity = profanity.contains_profanity(text): This line calls the contains_profanity function from the profanity module and passes the text variable as an argument. This function checks whether the provided text contains any profanity.

print(has_profanity): This line prints the result of the profanity check to the console. If the text contains any profanity, the result will be True; otherwise, it will be False.

After executing this code, the result printed to the console will indicate whether the provided text contains any profanity. Since the text "I can't believe he said that!" does not contain explicit profanity, the output will be False.



from better_profanity import profanity
custom_censor_words = ["heck", "darn", "frick"]
censor_word = profanity.load_censor_words(custom_censor_words)

#clcoding.com

Explanation:

The line from better_profanity import profanity imports the profanity module from the better_profanity library. This module provides functions and utilities for filtering and censoring offensive language in text.

Here's an explanation of the subsequent code:

custom_censor_words = ["heck", "darn", "frick"]: This line creates a list named custom_censor_words containing custom words that you want to be treated as profanity and censored.

censor_word = profanity.load_censor_words(custom_censor_words): This line calls the load_censor_words function from the profanity module and passes the custom_censor_words list as an argument. This function loads the custom censor words into the profanity filter.

However, there's a small correction here: The load_censor_words function doesn't return anything (None), so assigning its result to censor_word doesn't serve any purpose. It's primarily used to load the custom censor words into the profanity filter.

After executing this code, the profanity filter will include the custom censor words provided in the custom_censor_words list. Any occurrence of these words in the text will be censored according to the filter's settings.

Thursday 11 April 2024

Yellow Heart using Python ♥

 


Code : 

import turtle

t = turtle.Turtle()

t.shapesize(0.2, 0.2)

s = turtle.Screen()

s.bgcolor('black')


t.fillcolor("yellow")

t.begin_fill()


t.left(50)

t.forward(240)  

t.circle(90, 200)  

t.left(221)

t.circle(90, 200)  

t.forward(260)  


t.end_fill()


turtle.done()

#clcoding.com

Explanation: 

This code utilizes the Turtle module in Python to create a graphic using turtle graphics. Let's break down each part of the code:

import turtle: This line imports the Turtle module, which provides a drawing canvas and various methods for creating graphics using turtle graphics.

t = turtle.Turtle(): This creates a turtle object named t. The turtle object represents a turtle that can move around the screen and draw lines and shapes.

t.shapesize(0.2, 0.2): This line sets the size of the turtle shape. The parameters 0.2, 0.2 specify that the turtle's shape should be scaled to 20% of its default size in both the x and y directions.

s = turtle.Screen(): This creates a screen object named s. The screen object represents the window or canvas where the turtle will draw.

s.bgcolor('black'): This sets the background color of the screen to black.

t.fillcolor("yellow"): This sets the fill color of the turtle to yellow.

t.begin_fill(): This marks the beginning of a shape that will be filled with the fill color.

t.left(50): This turns the turtle left by 50 degrees.

t.forward(240): This moves the turtle forward by 240 units.

t.circle(90, 200): This draws a partial circle with a radius of 90 units and an extent of 200 degrees. This creates a curved shape.

t.left(221): This turns the turtle left by 221 degrees.

t.circle(90, 200): This draws another partial circle similar to the previous one.

t.forward(260): This moves the turtle forward by 260 units.

t.end_fill(): This marks the end of the shape to be filled and fills the shape with the specified fill color.

turtle.done(): This keeps the window open after the drawing is complete until the user closes it manually.

This code creates a graphic consisting of two curved shapes filled with yellow color on a black background.

Colorful Galaxy using Python

 


Code : 

import turtle

t = turtle.Turtle()

#clcoding.com 

s = turtle.Screen()

colors=['orange', 'red', 'magenta', 'blue', 'magenta',

        'yellow', 'green', 'cyan', 'purple']

s.bgcolor('black')

t.pensize('2')

t.speed(0)

for x in range (360):

    t.pencolor(colors[x%6])

    t.width(x//100+1)

    t.forward(x) 

    t.right(59)

    turtle.hideturtle()    

#clcoding.com    

Explanation: 

let's break down the code step by step:

import turtle: This line imports the Turtle module, which provides a graphics environment for drawing shapes and patterns.

t = turtle.Turtle(): This creates a new Turtle object named t. The Turtle object represents a pen that can draw on the screen.

s = turtle.Screen(): This creates a new Screen object named s. The Screen object represents the window or canvas where the turtle will draw.

colors = ['orange', 'red', 'magenta', 'blue', 'magenta', 'yellow', 'green', 'cyan', 'purple']: This is a list of colors that will be used for drawing. Each color is represented by a string.

s.bgcolor('black'): This sets the background color of the screen to black.

t.pensize(2): This sets the width of the pen to 2 pixels.

t.speed(0): This sets the drawing speed of the turtle to the fastest speed (0 means fastest).

for x in range(360):: This starts a loop that will repeat 360 times. The loop will draw a spiral pattern.

t.pencolor(colors[x % 6]): This sets the color of the pen to one of the colors from the colors list. The % operator is used to cycle through the colors repeatedly as x increases.

t.width(x // 100 + 1): This sets the width of the pen based on the current value of x. As x increases, the pen width will gradually increase.

t.forward(x): This moves the turtle forward by a distance equal to the current value of x.

t.right(59): This rotates the turtle to the right by 59 degrees.

turtle.hideturtle(): This hides the turtle cursor from the screen.

#clcoding.com: This appears to be a comment indicating the source or reference of the code.

Overall, this code creates a colorful spiral pattern using the Turtle module in Python.

Wednesday 10 April 2024

Fibonacci sequence in Python - 5 ways

 

import math


def fibonacci_closed_form(n):

    phi = (1 + math.sqrt(5)) / 2

    return round((phi**n - (-1/phi)**n) / math.sqrt(5))


# Define the number of Fibonacci numbers you want to print

num_terms = 5


# Print the Fibonacci sequence

for i in range(num_terms):

    print(fibonacci_closed_form(i))

#clcoding.com 

Explanation: 

The import math statement in Python allows you to access various mathematical functions and constants provided by the Python math module. These functions include trigonometric functions, logarithmic functions, and mathematical constants such as ฯ€ (pi) and e.

In the given code snippet, import math is used to access the sqrt() function from the math module. This function calculates the square root of a number.

The fibonacci_closed_form() function uses the golden ratio (phi) and its inverse to compute the nth Fibonacci number using Binet's formula. Binet's formula is a closed-form expression that directly calculates the nth Fibonacci number without recursion or iteration.

Here's a breakdown of the fibonacci_closed_form() function:

It calculates the golden ratio (phi) using the formula (1 + math.sqrt(5)) / 2.
Then, it uses phi and its inverse (-1/phi) to compute the nth Fibonacci number using Binet's formula: 

Finally, it rounds the result using the round() function to get the nearest integer, which is the nth Fibonacci number.
The code then prints the Fibonacci sequence for a specified number of terms (num_terms) using a loop. Each iteration of the loop calls the fibonacci_closed_form() function to compute the nth Fibonacci number and prints the result.



def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
sequence = fibonacci_generator()
for _ in range(6):
    print(next(sequence))

#clcoding.com 

Explanantion: 

Let's break down the code:

def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
This defines a generator function fibonacci_generator(). Generators are special functions in Python that allow you to generate a sequence of values lazily, i.e., one at a time, rather than generating them all at once and storing them in memory.

Inside the function, two variables a and b are initialized to 0 and 1 respectively. These variables are used to generate the Fibonacci sequence.
The while True loop creates an infinite loop, which means the generator will continue generating Fibonacci numbers indefinitely.
Inside the loop, the yield keyword is used to yield (or produce) the current value of a, making this function a generator. yield pauses the function's execution and returns a value to the caller without exiting the function.
After yielding a, the values of a and b are updated for the next iteration of the loop. This simulates the Fibonacci sequence generation logic where each number is the sum of the two preceding numbers.

sequence = fibonacci_generator()
for _ in range(6):
    print(next(sequence))
Here, fibonacci_generator() is called to create a generator object named sequence. This generator object will produce Fibonacci numbers when iterated over.

Then, a loop runs six times, each time calling next(sequence). This retrieves the next value from the generator sequence. The _ variable is used as a placeholder for the loop variable, as its value is not used inside the loop. The print() function then prints each Fibonacci number generated by the generator function.

So, the output of this code will be the first six Fibonacci numbers:

0
1
1
2
3
5
And the generator will continue to generate Fibonacci numbers if you keep calling next(sequence).




def fibonacci_memoization(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    else:
        memo[n] = fibonacci_memoization(n-1, memo) + fibonacci_memoization(n-2, memo)
        return memo[n]

# Define the number of Fibonacci numbers you want to print
num_terms = 6
# Print the Fibonacci sequence
for i in range(num_terms):
    print(fibonacci_memoization(i))
    
#clcoding.com 

Explanation: 

This code implements the Fibonacci sequence using memoization to optimize performance by avoiding redundant calculations. Let's break down how it works:

def fibonacci_memoization(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    else:
        memo[n] = fibonacci_memoization(n-1, memo) + fibonacci_memoization(n-2, memo)
        return memo[n]
The function fibonacci_memoization takes two parameters: n, which is the index of the Fibonacci number to compute, and memo, which is a dictionary used to store previously computed Fibonacci numbers to avoid redundant calculations.
It first checks if the Fibonacci number for index n is already in the memo dictionary. If it is, it returns the value directly from the memo, avoiding recalculation.
If the Fibonacci number for index n is not in the memo, it proceeds to compute it.
If n is 0 or 1, it returns n directly since the Fibonacci sequence starts with 0 and 1.
Otherwise, it recursively computes the (n-1)th and (n-2)th Fibonacci numbers using memoization, adds them together, stores the result in the memo dictionary, and returns the result.
This memoization technique ensures that each Fibonacci number is computed only once, significantly reducing the number of recursive calls needed to generate the sequence.

# Define the number of Fibonacci numbers you want to print
num_terms = 6
# Print the Fibonacci sequence
for i in range(num_terms):
    print(fibonacci_memoization(i))
Here, num_terms specifies the number of Fibonacci numbers to print.
The for loop iterates num_terms times, computing and printing each Fibonacci number using the fibonacci_memoization function.
When you run this code, it will print the first six Fibonacci numbers:

0
1
1
2
3
5
And it will continue generating Fibonacci numbers indefinitely if you continue calling fibonacci_memoization(i).
def fibonacci_recursive(n):
    if n <= 1:
        return n
    else:
        return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

# Define the number of Fibonacci numbers you want to print
num_terms = 5

# Print the Fibonacci sequence
for i in range(num_terms):
    print(fibonacci_recursive(i))

#clcoding.com 

Explanation: 

This code defines a recursive function fibonacci_recursive to generate the Fibonacci sequence. Let's break it down:

def fibonacci_recursive(n):
    if n <= 1:
        return n
    else:
        return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
The function fibonacci_recursive takes a single argument n, which represents the index of the Fibonacci number to compute.
If n is less than or equal to 1, meaning it's either 0 or 1, the function returns n itself. This is because the Fibonacci sequence starts with 0 and 1.
If n is greater than 1, the function recursively computes the (n-1)th and (n-2)th Fibonacci numbers by calling itself with n-1 and n-2, respectively, and then adds them together to get the nth Fibonacci number.

# Define the number of Fibonacci numbers you want to print
num_terms = 5

# Print the Fibonacci sequence
for i in range(num_terms):
    print(fibonacci_recursive(i))
Here, num_terms specifies the number of Fibonacci numbers to print.
The for loop iterates num_terms times, starting from 0 and ending at num_terms - 1. In each iteration, it computes and prints the Fibonacci number for the current index using the fibonacci_recursive function.
When you run this code, it will print the first five Fibonacci numbers:

0
1
1
2
3
And it will continue generating Fibonacci numbers indefinitely if you continue calling fibonacci_recursive(i). However, recursive Fibonacci calculation can become inefficient for large values of n due to redundant computations.






def fibonacci_iterative(n):
    fib_sequence = [0, 1]
    for i in range(2, n+1):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence

sequence = fibonacci_iterative(5)
print(sequence)

#clcoding.com 

Explanation: 

This code defines a function fibonacci_iterative to generate the Fibonacci sequence using an iterative approach. Let's go through it step by step:

def fibonacci_iterative(n):
    fib_sequence = [0, 1]
    for i in range(2, n+1):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence
The function fibonacci_iterative takes a single argument n, which represents the number of Fibonacci numbers to generate.
It initializes a list fib_sequence with the first two Fibonacci numbers, 0 and 1.
It then enters a loop starting from index 2 (since the first two Fibonacci numbers are already in the list) up to n. In each iteration, it calculates the next Fibonacci number by adding the last two numbers in the sequence (fib_sequence[-1] and fib_sequence[-2]) and appends it to the list.
After the loop completes, the function returns the entire list fib_sequence containing the generated Fibonacci sequence.

sequence = fibonacci_iterative(5)
print(sequence)
This code calls the fibonacci_iterative function with n = 5 to generate the first 5 Fibonacci numbers.
It then prints the generated sequence.
When you run this code, it will print the first 5 Fibonacci numbers:

[0, 1, 1, 2, 3, 5]
This iterative approach is efficient and straightforward for generating Fibonacci numbers, especially for small values of n.

Monday 8 April 2024

IP Address Infromation using Python

 

Code : 

import os

import urllib.request as urllib2

import json


# Use a while loop to continuously prompt the user for the target IP address

while True:

    # Prompt the user to input the target IP address

    ip = input("What is your target IP: ")

    

    # Construct the URL for the ip-api.com JSON API

    url = "http://ip-api.com/json/"

    

    # Send a request to the ip-api.com API to retrieve the geolocation information

    response = urllib2.urlopen(url + ip)

    

    # Read the response data

    data = response.read()

    

    # Parse the JSON response data into a Python dictionary

    values = json.loads(data)

    

    # Print the geolocation information for the target IP address

    print("IP: " + values["query"])

    print("City: " + values["city"])

    print("ISP: " + values["isp"])

    print("Country: " + values["country"])

    print("Region: " + values["region"])

    print("Timezone: " + values["timezone"])

    

    # Exit the loop after printing the information once

    break

#clcoding.com 

Explanation: 

This code snippet is a Python script that continuously prompts the user to input a target IP address and then retrieves geolocation information for that IP address using the ip-api.com JSON API. Let's break down each part of the code:

import os: This imports the os module, which provides a way to interact with the operating system. However, it's not used in this particular snippet.

import urllib.request as urllib2: This imports the urllib.request module under the alias urllib2. This module provides functionality for making HTTP requests, which is used to fetch data from the ip-api.com API.

import json: This imports the json module, which provides functions for encoding and decoding JSON data.

The code then enters a while True loop, which means it will continue to run indefinitely until explicitly stopped.

Inside the loop, the user is prompted to input a target IP address using the input() function. The IP address is stored in the variable ip.

The URL for the ip-api.com JSON API is constructed as http://ip-api.com/json/.

A request is made to the ip-api.com API using urllib2.urlopen(), passing in the constructed URL along with the target IP address.

The response data is read using the read() method of the response object.

The JSON response data is parsed into a Python dictionary using json.loads(), storing the result in the variable values.

The geolocation information extracted from the JSON response is printed to the console, including the IP address, city, ISP, country, region, and timezone.

Finally, the loop breaks after printing the information once, effectively ending the program.

This script allows users to input a target IP address and quickly obtain geolocation information about it using the ip-api.com API.

Plant Leaf using Python

 

import numpy as np

import matplotlib.pyplot as plt

t = np.linspace(0, 39*np.pi/2, 1000)

x = t * np.cos(t)**3

y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t)

plt.plot(x, y, c="green")

plt.show()

#clcoding.com

Explanation: 

This code snippet is written in Python and utilizes two popular libraries for numerical computing and visualization: NumPy and Matplotlib.

Here's a breakdown of what each part of the code does:

import numpy as np: This line imports the NumPy library and allows you to use its functionalities in your code. NumPy is a powerful library for numerical computations in Python, providing support for arrays, matrices, and mathematical functions.

import matplotlib.pyplot as plt: This line imports the pyplot module from the Matplotlib library, which is used for creating static, animated, and interactive visualizations in Python. It's typically imported with the alias plt for convenience.

t = np.linspace(0, 39*np.pi/2, 1000): This line generates an array t of 1000 equally spaced values ranging from 0 to 
39
2
2
39ฯ€
 . np.linspace() is a NumPy function that generates linearly spaced numbers.

x = t * np.cos(t)**3: This line computes the x-coordinates of the points on the plot. It utilizes NumPy's array operations to compute the expression 
×
cos
(
)
3
t×cos(t) 
3
 .

y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t): This line computes the y-coordinates of the points on the plot. It's a more complex expression involving trigonometric functions and mathematical operations.

plt.plot(x, y, c="green"): This line plots the x and y coordinates as a line plot. The c="green" argument specifies the color of the line as green.

plt.show(): This line displays the plot on the screen. It's necessary to call this function to actually see the plot.

Overall, this code generates a plot of a parametric curve defined by the equations for x and y. The resulting plot will depict the curve in green.



import numpy as np
import matplotlib.pyplot as plt

# Define the parameter t
t = np.linspace(0, 39*np.pi/2, 1000)

# Define the equations for x and y
x = t * np.cos(t)**3
y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t)

# Define the segment indices and corresponding colors
segments = [
    (0, 200, 'orange'),  # Green segment
    (200, 600, 'magenta'),   # Red segment
    (600, 1000, 'red')  # Orange segment
]

# Plot each segment separately with the corresponding color
for start, end, color in segments:
    plt.plot(x[start:end], y[start:end], c=color)

plt.show()
#clcoding.com 









Playing a YouTube Video using Python

 

import pywhatkit

# Using Exception Handling to avoid unprecedented errors

try:

    # Ask the user to input the song name

    song = input("Enter Song Name: ")

    # Play a YouTube video corresponding to the search term entered by the user

    pywhatkit.playonyt(song)    

    # Print a success message if the video is played successfully

    print("Successfully Played!") 

except:

    # Handle exceptions and print an error message if any unexpected error occurs

    print("An Unexpected Error!")


Explanation:

Importing the Module: import pywhatkit imports the pywhatkit module, which provides various functionalities, including playing YouTube videos.


Exception Handling (try-except): The code is wrapped in a try block, which allows Python to attempt the code within it. If an error occurs during the execution of the code inside the try block, Python will stop executing that block and jump to the except block.


User Input: Inside the try block, the input() function prompts the user to enter the name of the song they want to play on YouTube. The entered song name is stored in the variable song.


Playing YouTube Video: The pywhatkit.playonyt() function is called with the song variable as an argument. This function opens a web browser and plays the YouTube video corresponding to the search term entered by the user.


Success Message: If the video is played successfully without any errors, the code inside the try block will execute completely, and the success message "Successfully Played!" will be printed.


Exception Handling (except): If any unexpected error occurs during the execution of the code inside the try block, Python will jump to the except block and execute the code within it. In this case, it simply prints the error message "An Unexpected Error!". This ensures that the program does not crash abruptly if an error occurs during video playback.


Overall, this code allows users to input the name of a song, and it plays the corresponding YouTube video while handling any unexpected errors that may occur during execution.

Sending a WhatsApp Message using Python

 

# importing the module

import pywhatkit


# using Exception Handling to avoid unprecedented errors

try:


# sending message to receiver using pywhatkit

    pywhatkit.sendwhatmsg("+919767292502","Hello Python",21, 23)

    print("Successfully Sent!")

except:


# handling exception and printing error message

    print("An Unexpected Error!")

Here's what each part does:

Importing the Module: import pywhatkit imports the pywhatkit module, which provides various functionalities, including sending WhatsApp messages.

Exception Handling (try-except): The code is wrapped in a try block, which allows Python to attempt the code within it. If an error occurs during the execution of the code inside the try block, Python will stop executing that block and jump to the except block.

Sending WhatsApp Message: Inside the try block, the pywhatkit.sendwhatmsg() function is called to send a WhatsApp message. It takes four arguments: the recipient's phone number (including the country code), the message content, the hour of the day (in 24-hour format) at which the message will be sent, and the minute of the hour.

Success Message: If the message is sent successfully without any errors, the code inside the try block will execute completely, and the success message "Successfully Sent!" will be printed.

Exception Handling (except): If any unexpected error occurs during the execution of the code inside the try block, Python will jump to the except block and execute the code within it. In this case, it simply prints the error message "An Unexpected Error!". This ensures that the program does not crash abruptly if an error occurs during message sending.

Saturday 6 April 2024

Wednesday 3 April 2024

Convert PDF files using Python


from gtts import gTTS
from PyPDF2 import PdfReader

def pdf_to_text(pdf_file):
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page = reader.pages[page_num]
            text += page.extract_text()
    return text

def text_to_audio(text, output_file):
    tts = gTTS(text)
    tts.save(output_file)

# Example usage:
pdf_file = "clcoding.pdf"
output_audio_file = "clcoding_audio.mp3"

text = pdf_to_text(pdf_file)
text_to_audio(text, output_audio_file)

#clcoding.com

Explanation: 

This code snippet is a Python script that converts text from a PDF file to an audio file using the Google Text-to-Speech (gTTS) library (gTTS) and the PyPDF2 library (PdfReader).

Here's a breakdown of what each part of the code does:

Importing Required Libraries:

from gtts import gTTS: This imports the gTTS class from the gtts module, which allows us to convert text to speech using Google Text-to-Speech.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
pdf_to_text(pdf_file) Function:

This function takes a PDF file path (pdf_file) as input.
It opens the PDF file in binary mode and creates a PdfReader object to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) and extracts text from each page using the extract_text() method.
It concatenates all the extracted text from each page into a single string (text).
Finally, it returns the concatenated text.
text_to_audio(text, output_file) Function:

This function takes two arguments: the text to convert to audio (text) and the file path where the audio will be saved (output_file).
It creates a gTTS object (tts) by passing the input text.
It saves the generated audio file to the specified output file path.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output audio file path (output_audio_file) as "clcoding_audio.mp3".
It calls the pdf_to_text() function to extract text from the PDF file.
It calls the text_to_audio() function to convert the extracted text to audio and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script essentially converts the text content of a PDF file into audio, which could be useful for tasks such as creating audiobooks, generating voiceovers, or assisting users with reading disabilities.

import os
from PyPDF2 import PdfReader
from pdf2image import convert_from_path

def pdf_to_images(pdf_file, output_dir):
    images = []
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num, _ in enumerate(reader.pages):
            # Convert each PDF page to image
            img_path = os.path.join(output_dir, f"page_{page_num}.png")
            images.append(img_path)
    return images

# Example usage:
pdf_file = "clcoding.pdf"
output_dir = "output_images"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

pdf_to_images(pdf_file, output_dir)

#clcoding.com

Explanation: 

This Python script converts each page of a PDF file into an image format (PNG) using the PyPDF2 library to read the PDF and the pdf2image library to perform the conversion.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pdf2image import convert_from_path: This imports the convert_from_path function from the pdf2image library, which is used to convert PDF pages to images.
pdf_to_images(pdf_file, output_dir) Function:

This function takes two arguments: the path to the input PDF file (pdf_file) and the directory where the output images will be saved (output_dir).
It initializes an empty list called images to store the file paths of the converted images.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using enumerate to get both the page number and the page object.
For each page, it generates a file path for the corresponding image in the output directory (output_dir) using os.path.join and appends it to the images list.
Finally, it returns the list of image file paths.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output directory (output_dir) as "output_images".
It checks if the output directory does not exist (if not os.path.exists(output_dir)), and if not, it creates the directory using os.makedirs(output_dir).
It calls the pdf_to_images() function to convert the PDF pages to images and stores the list of image file paths.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for tasks such as converting PDF pages to images for further processing or display, such as in document management systems, image processing pipelines, or for creating thumbnails of PDF documents.

import os
from PyPDF2 import PdfReader
import docx

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_docx(output_file):
    text = pdf_to_text()
    doc = docx.Document()
    doc.add_paragraph(text)
    doc.save(output_file)

# Example usage:
output_docx_file = "output_docx.docx"

pdf_to_docx(output_docx_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a Microsoft Word document (.docx) using the PyPDF2 library to extract text from the PDF and the python-docx library to create and save the Word document.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import docx: This imports the docx module, which is part of the python-docx library, used for creating and manipulating Word documents.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_docx(output_file) Function:

This function converts the extracted text from the PDF to a Word document.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new docx.Document() object (doc) to represent the Word document.
It adds a paragraph containing the extracted text to the document using the add_paragraph() method.
It saves the document to the specified output file path using the save() method.
Example Usage:

It defines the output Word document file path (output_docx_file) as "output_docx.docx".
It calls the pdf_to_docx() function to convert the PDF text content to a Word document and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script is useful for converting the text content of a PDF file to a Word document, which can be helpful for further editing or formatting. Make sure you have the necessary libraries installed (PyPDF2 and python-docx).

 import os
from PyPDF2 import PdfReader
import pandas as pd

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_excel(output_file):
    text = pdf_to_text()
    lines = text.split('\n')
    df = pd.DataFrame(lines)
    df.to_excel(output_file, index=False, header=False)

# Example usage:
output_excel_file = "output_excel.xlsx"

pdf_to_excel(output_excel_file)

#clcoding.com

Explanation:

This Python script reads the text content of a PDF file ("clcoding.pdf") and then converts it into an Excel file (.xlsx) using the Pandas library. Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import pandas as pd: This imports the Pandas library, often used for data manipulation and analysis.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_excel(output_file) Function:

This function converts the extracted text from the PDF to an Excel file.
It calls the pdf_to_text() function to get the text content of the PDF.
It splits the text into lines using the newline character ('\n') and creates a list of lines.
It creates a Pandas DataFrame (df) from the list of lines.
It saves the DataFrame to an Excel file specified by the output_file parameter using the to_excel() method, without including the index or header.
Example Usage:

It defines the output Excel file path (output_excel_file) as "output_excel.xlsx".
It calls the pdf_to_excel() function to convert the PDF text content to an Excel file and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for extracting text data from PDF files and converting it into a structured format like an Excel spreadsheet for further analysis or manipulation. Make sure you have the necessary libraries installed (PyPDF2 and pandas).



import os
from PyPDF2 import PdfReader
from pptx import Presentation

def pdf_to_text():
    pdf_file = "clcoding.pdf"  # Using "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_ppt(output_file):
    text = pdf_to_text()
    prs = Presentation()
    slides = text.split('\n\n')
    for slide_content in slides:
        slide = prs.slides.add_slide(prs.slide_layouts[1])
        slide.shapes.title.text = slide_content
    prs.save(output_file)

# Example usage:
output_ppt_file = "output_ppt.pptx"

pdf_to_ppt(output_ppt_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a PowerPoint presentation (.pptx) using the PyPDF2 library to extract text from the PDF and the python-pptx library to create and save the PowerPoint presentation.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pptx import Presentation: This imports the Presentation class from the pptx module, which is part of the python-pptx library used for creating and manipulating PowerPoint presentations.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_ppt(output_file) Function:

This function converts the extracted text from the PDF to a PowerPoint presentation.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new Presentation() object (prs) to represent the PowerPoint presentation.
It splits the text into slides based on double newline characters ('\n\n').
For each slide content, it adds a new slide to the presentation using the add_slide() method, specifying the layout of the slide.
It sets the title of each slide to the slide content using the shapes.title.text property.
Finally, it saves the presentation to the specified output file path using the save() method.
Example Usage:

It defines the output PowerPoint file path (output_ppt_file) as "output_ppt.pptx".
It calls the pdf_to_ppt() function to convert the PDF text content to a PowerPoint presentation and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for converting the text content of a PDF file into a structured format like a PowerPoint presentation, which can be helpful for presentations or sharing information in a visually appealing format. Make sure you have the necessary libraries installed (PyPDF2 and python-pptx).

Tuesday 2 April 2024

Doughnut Plot using Python

 

import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]

colors = ['#FFA07A', '#FFD700', '#6495ED', '#ADFF2F']


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5, marker=dict(colors=colors))])

fig.update_traces(textinfo='percent+label', textfont_size=14, hoverinfo='label+percent')

fig.update_layout(title_text="Customized Doughnut Plot", showlegend=False)


# Show plot

fig.show()


#clcoding.com


import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]

explode = (0, 0.1, 0, 0)  # "explode" the 2nd slice


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90, shadow=True, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot with Exploded Segment and Shadow Effect')


# Show plot

plt.show()


#clcoding.com



import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5)])

fig.update_layout(title_text="Doughnut Plot")


# Show plot

fig.show()


#clcoding.com



import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot')


# Show plot

plt.show()


#clcoding.com

Sunday 31 March 2024

Happy Easter wishes using Python

 


import pyfiglet

from termcolor import colored


def wish_happy_easter():

    # Creating a colorful Happy Easter message using pyfiglet and termcolor

    easter_message = pyfiglet.figlet_format("Happy Easter!")

    colored_message = colored(easter_message, color='yellow', attrs=['bold'])

    

    # Additional colorful text

    additional_text = colored("\nWishing you a joyful and blessed Easter !")

    

    print(colored_message + additional_text)


wish_happy_easter()


#clcoding.com

Thursday 28 March 2024

pytube library for downloading YouTube videos

 

# Get a specific stream
stream = yt.streams.get_by_itag(22)  # Example: iTAG for 720p MP4

# Download the stream
stream.download()

#clcoding.com 

# Get the best audio stream
audio_stream = yt.streams.get_audio_only()

# Download the audio
audio_stream.download()

#clcoding.com 





# Get streams with only audio
audio_streams = yt.streams.filter(only_audio=True)

# Get streams with only video
video_streams = yt.streams.filter(only_video=True)

# Get streams with a specific resolution
hd_streams = yt.streams.filter(res="720p")

#clcoding.com 

# Get all available streams

streams = yt.streams.all()


# Print available streams

for stream in streams:

    print(stream)


#clcoding.com 

# Get streams with only audio

audio_streams = yt.streams.filter(only_audio=True)


# Get streams with only video

video_streams = yt.streams.filter(only_video=True)


# Get streams with a specific resolution

hd_streams = yt.streams.filter(res="720p")


#clcoding.com 



# Title of the video

print("Title:", yt.title)


# Description of the video

print("Description:", yt.description)


# Thumbnail URL of the video

print("Thumbnail URL:", yt.thumbnail_url)


# Video length in seconds

print("Length (seconds):", yt.length)


# Number of views

print("Views:", yt.views)


#clcoding.com 




from pytube import YouTube


# YouTube video URL

video_url = 'https://www.youtube.com/watch?v=qMNKy_4opeE'


# Initialize a YouTube object with the video URL

yt = YouTube(video_url)


# Get the highest resolution stream

stream = yt.streams.get_highest_resolution()


# Download the video

stream.download()


print("Download completed!")


#clcoding.com 

Tuesday 26 March 2024

How to install modules without pip ?

 Installing Python modules without using pip can be done manually by downloading the module's source code or distribution package and then installing it using Python's setup tools. Here's a basic guide on how to do it:

Download the module: Go to the official website or repository of the module you want to install and download the source code or distribution package (usually in a .tar.gz or .zip format).

Extract the package: Extract the downloaded package to a directory on your computer.

Navigate to the package directory: Open a terminal or command prompt and navigate to the directory where you extracted the package.

Install the module: Run the following command to install the module using Python's setup tools:

python setup.py install

If you have multiple versions of Python installed, you may need to specify the Python version explicitly, for example:

python3 setup.py install

This command will compile and install the module into your Python environment.

Verify installation: After installation, you can verify if the module is installed correctly by trying to import it in a Python script or interpreter.

Keep in mind that installing modules manually without pip may require additional dependencies and manual handling of version compatibility. It's generally recommended to use pip whenever possible, as it handles dependency resolution and installation automatically. However, manual installation can be useful in cases where pip is not available or suitable for some reason.







Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (741) Python Coding Challenge (192) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses