Trending February 2024 # Full Guide On Whatsapp Automation Using Python # Suggested March 2024 # Top 3 Popular

You are reading the article Full Guide On Whatsapp Automation Using Python updated in February 2024 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Full Guide On Whatsapp Automation Using Python

This article was published as a part of the Data Science Blogathon.

Overview

Introduction

What is Whatsapp automation using python?

What are its features?

Let’s code!

Errors and exceptions

Handling error

Can we do it another way?

Conclusion

 Introduction

Imagine, you turned on your pc, a message “Good Morning!” is automatically sent to your WhatsApp contact without having done anything. And this is what we are going to create and with various other features.

What is Whatsapp Automation Using Python?

It is a utility and the best python software that will save your time and will make you a punctual person in other person’s views. It will basically automate WhatsApp web and send the message.

What are its Features?

So let’s understand it backwards, what are its features and how will it work.

You turned on your pc,

This program will run automatically

Wait for 2 minutes to not load to pc (as many programs run simultaneously when a pc starts like antivirus programs and many more which slows down the pc and this program will wait to not load the pc)

Check the file (database of the program)

If it does not exist,

it will create the file and will send the message and then update the file.

if it exists,

Then, will check if the last date (the database will have the dates of the message sent ) is of another year and if yes it will delete all the contents of the file (to free up the space taken by it) and will send the message and it will again update the current date to the file.

And if the last date’s year is the same as the current year, it will directly move forward.

If the last date in the file is not the current date, then it will send the message and update the database.

And if the last date in the file is the current date, then it will just check for the last year’s date and will close the program.

If there is a problem in sending the message, it will not update the database and will notify the user that there is a problem in sending the message.

Whatsapp logo

Let’s code!

As we have known all the things that our program will do. So now we will start creating our program.

First of all, we will need to download the modules/libraries required to work with the program

And the modules are “time”, “datetime”, “selenium”, “os”, “plyer”

Out of all these modules, only Selenium (here its version: 3.141.0) and plyer (here its version: 2.0.0) module needs to be downloaded and other remaining comes preinstalled with python 3.

So using this command in this terminal, you can download and install all these modules.

pip install selenium plyer

Now we have installed the modules and now we can import them into our program and use it. And below we will start our coding.

import time time.sleep(120) import datetime from selenium import webdriver from selenium.webdriver.chrome.options import Options from chúng tôi import Keys import os from plyer import notification

As we will make our program automatically started at the start of the pc, we will make our program sleep for 2 minutes to not load on our pc (As explained in the what are its features section ).  On the first line of our program, we have imported the time module then in the second line, we made our program sleep. And line after line we will import all the modules like in third line, datetime module, fourth line webdriver class from selenium and in next line options from selenium and again in next line Keys from selenium and after that, we have imported os module and at last, we have imported notification from plyer (Same as our infinite timer using python program ).

Below is why we are importing all these modules

time – mainly for making our program sleep

datetime – To work with dates and years (To update the database)

webdriver – It is used to work with the browser and the website

Options – It is used to add arguments to the browser like which extensions to use and which user account to use and maximize the window and much more.

Keys – It is used to work with the keys of the keyboard or hotkeys like Ctrl+A and Ctrl+C or Enter.

os – Exiting the program

notification – For notification (If an error occurs while sending the message, as explained in what are its features section )

Note: YOU CAN ADJUST THE SLEEP TIME ACCORDING TO YOUR CONVENIENCE. IF YOUR PC IS ALWAYS CONNECTED TO A WIFI OR ETHERNET, THEN YOU CAN DECREASE THE SLEEP TIME OR IF YOUR PC IS FAST ENOUGH, THEN ALSO YOU CAN DECREASE THE SLEEPING TIME AS IT IS DEPENDENT ON PC TO PC.

Now the main messenger() function starts here

def messenger(): try: message_content = "Good morning!" options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path=path, options=options) driver.minimize_window() driver.get(url) time.sleep(20) type_it = driver.find_elements_by_class_name('_13NKt') time.sleep(20) try: type_it[1].send_keys(message_content + Keys.ENTER) except IndexError as e:

time.sleep(20)

  type_it = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[1]/div[4]/div[1]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]')

       

type_it.send_keys(message_content+ Keys.ENTER)

print(e) time.sleep(10) driver.quit() except Exception as e: notification.notify( title = "Whatsapp message not sent", message = "Error while sending!", app_name = "Whatsapp Message error", toast = True, ) print(e) os._exit(0)

In the first line of the above code, we have defined the messenger() function. Since in the automation process, there may be some errors ( like internet problems or any other issue ). So we will use try-except block to make our program error-free.

Therefore, we have to use the try method in the second line. In the next line, we have created the variable url which will contain the url of the Whatsapp web ( Url will contain the phone number of the person to whom you want to send the message ). And in the next line, we have the variable message_content ‘ (You can change it as you want) which will contain the message to be sent.

And in the next line, we have the variable message_content which will contain the message to be sent. The next line contains the path variable which will contain the path of the chrome driver (Note: The ‘r’ (r is used for raw string )behind string is used to not escape the escape characters, like ‘/n’ is used to get a new line and if you want to print it, then it will not get printed, just a new line will be printed. To print it, we can use either ‘//n’ or r’/n’, Both will print the characters ‘/n’. And in a path like ‘C:/users’, ‘/’ may raise any issue, so we are using it for raw string ). More about the path in the handling section. 

BONUS: You can’t use WhatsApp Web without scanning the QR code. You have to scan the QR minimum of 1 time and then if you checked the keep me signed in option, you can visit the site directly without scanning the QR again. And if you are using another profile of the browser which doesn’t have WhatsApp logged in, then you have to scan the QR again. But what you can do is just join the beta mode of WhatsApp, and you will have no issue sending the message. More on this in the handling error section.

In the next line, we have variable ‘options’ which will contain the ChromeOptions(). It is just used to work with the profiles, extensions, cookies or proxies, and stuffs like that on the browser. In the next line, we have added the argument which contains the profile in which WhatsApp is logged in. In the next line, the driver variable is used which initializes the Chrome with the chrome driver as specified above and the options for the profile as an argument.

In the next line, we have minimized the screen for just working in the background type. Next, we have a driver variable that will get the URL in the browser. Now we will make our program sleep for 20 seconds to not get any error in accessing the elements of the site (As the website may take time to load and elements of the site may not be loaded quickly). In the next line, we have variable type_it, which will contain the list of the elements of the given class name of the element. NOTE: THE CLASSES AND XPATH MAY HAVE CHANGED WHEN YOU ARE READING THIS, SO FIND YOUR CLASS NAME FOR THE TYPING BOX AND THEN USE IT. Again we will make the program sleep for 20 seconds. Then we will use the second element from the list for sending the message and will use keys. ENTER to send the message using Keys that we have imported earlier. We will use try and except because sometimes it is not able to access the element and will throw the Indexerror. And if it happens, we will try it again and then send it using its ‘Xpath’. After that, we will make our program sleep, as if it is sent from our program but due to instant use of quit method to quit the driver, it may not send it sometimes.

And if any error happens in sending, then it will simply send the user a notification. For that, we have to use notify function of the imported notification from the plyer module. As we have done in infinite timer using python, we will send the desktop notification to the user. To know more about what is done here, just refer to another article which is infinite timer using python. At the last of the error happened, we will just quit the program as we don’t need to do any work now. So we will use the _exit(0) function of the os module with ‘0’ to say everything is fine in the program to the system.

Now we have to work only on the database section.

today = str(datetime.date.today()) today_2 = f"{today} " content = bytes(today_2,'utf-8') year_str = str(datetime.datetime.now().year) year_edit = bytes(year_str,'utf-8').decode('utf-8') date_str = str(datetime.datetime.now().day) date_edit = bytes(date_str,'utf-8').decode('utf-8') edit = {"1":"01", "2":"02", "2":"03", "4":"04", "5":"05", "6":"06", "7":"07", "8":"08", "9":"09",} print(date_edit) try: file = open("database.txt", "x") messenger() file.write(today_2) file.close() except Exception as e: file = open("database.txt", "a+b") try: try: file.seek(-11,2) # seek will not work in negative in text mode, only in byte mode except OSError as e: print(e) messenger() file.write(content) file.close() os._exit(0) year = file.read(10).decode('utf-8') file.seek(-11,2) date = file.read(10).decode('utf-8') if year_edit != year[:4]: file.close() file = open("database.txt", "wb") file.close() file = open("database.txt", "a+b") messenger() file.write(content) file.close() for x in edit.keys(): if x == date_edit: date_edit = edit.get(x) break if date_edit != date[8:14]: messenger() file.write(content) file.close() os._exit(0) except Exception as e: print(e)

Now the main thing is we will use datetime module to get the date, year, and all. Since datetime object is of type ‘datetime’ not ‘str’ (string in python ), there will an error in writing this to the file. So we have to convert it to ‘str’ and also we have to convert all these to bytes to read and write in the file in bytes mode. But one of the bugs of the datetime module in our program can be the dates, like the date, 2023-01-01 will be 2023-1-1 as per datetime module. Now if we check the last date in our database to check if the message was sent on that date or not, we will get a wrong answer as both are different. So we will fix this bug by making a dictionary of the digits (technically string) to that of the required digit (Again string).

NOTE: YOU MUST CLOSE THE FILE AFTER OPENING IT BECAUSE SOMETIMES IT DOESN’T SAVE THE FILE AND YOUR WORK WILL NOT BE DONE.

And if there is an error like there is the database already in the directory, then it will directly enter into except block and will open the file in read + write mode in bytes like “a+b”.

And if the file has contents, then it will read the year and decode it to normal encodings which is ‘utf-8’ and then we will seek the file pointer to a position from where it can read the specific date in the file and again decode it.

First, it will check if the year in the file is not the current year, then it will close the file opened in ‘appending and reading in bytes mode’ and then open it in writing and bytes mode (it will clear all the contents of the file ). Then it will simply close the file as all contents are deleted from the file and then we will again open the file in ‘a+b’ mode and call the messenger() function and then update the file with the current date and then close it. And the program is closed now.

The bug we have solved above will be used, using for loop it will change the contents of the date_edit variable using the dictionary keys.

And if there is an error while the running of the program, it will simply handle it and will print the problem.

Errors and Exceptions

You will have an error when WhatsApp will not load or will ask for QR. Or your chromedriver is of another version as of your chrome version.

This program may not send messages every time.

Reasons

Due to improper internet connection

Due to not working of webdriver

Due to high usage of ram in the background

And these may not notify you about the message not be being sent because according to our program all these will be handled by our webdriver and it will not get into exception handling. But every time you start your pc, it will try to message if it is not sent.

Exception Handling

You can join Whatsapp beta to manage the QR error. To join beta mode on WhatsApp, you can read this article

Chromedriver

First of all, you have to check for the version of your chrome and then just google for the chromedriver of that version and then download it and you are all done.

Tip: YOU CAN’T USE YOUR WHATSAPP WEB PROFILE  WHEN THIS PROGRAM IS RUNNING OR THE PROGRAM WILL CRASH. SO YOU CAN CHANGE THE SLEEP TIME OF THE PROGRAM ACCORDINGLY.

So in case you want to use the browser, you have to use another browser, not the browser that our program will use.

And yes, you can regulate the sleep time of your program according to your pc, ram, internet connection.

Can we do it another way?

Yes, but no! This software which is made manually can be replaced by various modules. But all those modules will have the same kind of code or maybe different from ours but we can use it. It is like we bought noodles and cooked them or we can just make raw noodles ourselves and then cook them. In both cases, we have cooked noodles, but by buying and cooking, it becomes hassle-free but you can’t add flavor to that raw noodle, on the other hand making noodles on our own takes time and sometimes hassles, but it is worth doing as you can do what you want with your raw noodles. So there are many alternatives to this and one of which is pywhatkit. It is also a very lightweight, easy to use, and fantastic module that is also worth practicing. I will definitely try to make an article on this in the future.

Conclusion

Woohoo! you made your own beast WhatsApp automating software with its own database.

Now you must try it yourself to fully enjoy the simplicity of python.

There is no specific output of this program but this is the image of the message sent.

snapshot of the sent message

To do this in windows, the steps are following.

Now your program will run automatically at the startup of your computer

About

I am Atulya Khatri, a python geek. I love to learn different programming languages, try different libraries and create different programming kinds of stuff.

My other articles are as follows-

Gui Calculator using python

Beginners guide to password generator using python

Building an infinite timer using python

Youtube Video Downloader using Python

Images on this page.

1st: Photo by Alexander Shatov on Unsplash

2nd: Photo by author

Do share this with all your friends who you think need this.

Happy coding : )

The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.

Related

You're reading Full Guide On Whatsapp Automation Using Python

Python Full Stack Vs Java Full Stack Developers: Who Earns More?

Python and Java Full stack developers are in-demand for the Software IT Industry. Let’s explore more

Java is best suited for programs like desktop GUI apps, mobile apps, enterprise solutions, and embedded systems and middleware products. Whereas Python works best for prototyping, machine learning apps, OS, language development, games, and graphic designing/image processing. When it comes to the earning part, all full-stack developers earn a great sum. And to earn well one will require certain skills whether they want to become Java Full stack developer or a Python full stack developer. According to Payscale Data, the average salary of a Java Full stack developer is INR 6.50 lac whereas, Python full stack developer earns around 3.50 lac.

Java Full Stack Developer Skills

Java Full stack developer is the in-demand for the Software IT Industry. Today’s tech companies need developers who just do not code but are also good solution architects, developers, testers, and designers. Full Stack Java Developer position is one such end-to-end developer who takes care of end-to-end product development with expertise in Java and other related technologies. Here are certain skills you need to learn to become the best Java Full stack developer:

1. Object-Oriented Programming:

OOP concepts help developers identify and debug Java code with ease. It also allows developers to construct fully reusable apps with less code and in less time.

2. JVM Internals:

It is critical for Java developers to master JVM internals – what are the different JVM elements and how they function, JIT, JVM options, garbage collections, collectors, etc.

3. Databases & Web Storage:

A database is where all the project data is stored securely. It helps different teams work collaboratively on the same project and be well-aware of the progress.

Java full stack developers are expected to be familiar with common DevOps tools like Maven, Docker, Ansible, and Kubernetes. DevOps is a must-have skill for professional developers.

5. Web Architecture:

Developers should know the structural elements and user interface elements of the web application like – DNS or Domain Name System, Database Servers, and Cloud Storage.

Python Full Stack Developer Skills

Python is designed to promote code readability. It is simple, straightforward, and versatile; making it the ideal choice for a wide range of projects, from simple web applications to operating systems. A full-stack developer works on the frontend and backend. In simple words, a full-stack developer creates a website that has an effective look and efficient functionality.

1. Front-end Languages:

Expert Python developers should have in-depth knowledge of the front-end languages such as JavaScript, HTML5, and CSS3 and understand their potential.

2. Debugging Skills:

They should be familiar with different ways to debug, for example – printing out variable values, modifying the path of the program, and using a debugger.

3. Machine Learning & Artificial Intelligence:

Having mastery over ML and AI algorithms can give developers a competitive edge in a world where data science is at the center of it all.

4. Python Shell:

Understanding how to leverage Python Shell is incredibly important because it can help developers save a lot of time when it comes to testing the newly written codes.

5. Object Relational Mapper:

ORMs (Object Relational Mappers) help with building virtual object databases. With ORMs, one can keep writing in Python code without using SQL to build and update data schemas.

Visualizing Netflix Data Using Python!

Image Source

We can say that data visualization is basically a graphical representation of data and information. It is mainly used for data cleaning, exploratory data analysis, and proper effective communication with business stakeholders. Right now the demand for data scientists is on the rise. Day by day we are shifting towards a data-driven world. It is highly beneficial to be able to make decisions from data and use the skill of visualization to tell stories about what, when, where, and how data might lead us to a fruitful outcome.

Data visualization is going to change the way our analysts work with data. They’re going to be expected to respond to issues more rapidly. And they’ll need to be able to dig for more insights – look at data differently, more imaginatively. Data visualization will promote that creative data exploration. -Simon Samuel

Table of contents

Why do we need Data Visualization?

Types of Data Visualization.

Brief about tools we will be using

Data pre-processing

Data Visualization

Keep in mind

Conclusion

Why do we need good Data Visualizations?

Our eyes are drawn to colours and patterns. We can quickly recognize blue from yellow, circle from a square. Data visualization is a form of visual art that not only grabs our interests but also keeps our eyes on the message. We can literally narrate our entire numerical data to the stakeholders in a form of captivating graphs with the help of data visualization.

Right now we are living in “an age of Big data” trillions of rows of data are being generated every day. Data visualization helps us in curating data into a form that is easily understandable and also helps in highlighting a specific portion. Plain graphs are too boring for anyone to notice and even fail to keep the reader engaged. Hence, today we will be seeing how to create some mind-blowing visualization using matplotlib and seaborn.

Types of Data visualization

In this article we will be creating two types of Data visualization:

1. Bar Plot( Horizontal ): 

It is a graph that represents a specific category of data with rectangular bars with length and height proportional to the values they represent.

Syntax: matplotlib.pyplot.barh(y,width,height) 

Parameters: 

Y: Co-ordinates of the Y bar.

Width: Width of the bar.

Height: Height of the bar.

2. Timeline (Customized Horizontal line):

Syntax: axhline(y=0, xmin=0, xmax=1, c, zorder )

Parameters:

Y: Co-ordinates of Y in a horizontal line with a default value of 0.

xmin: This parameter should be between 0 and 1. 0 means the extreme left of the plot and 1 means the extreme right of the plot with 0 being the default value.

xmax: This parameter should be between 0 and 1. 0 means the extreme left of the plot and 1 means the extreme right of the plot with 1 being the default value.

Before we get started, I want you to know that we won’t be using any python library other than Matplotlib, seaborn and we will be using Netflix’s dataset for the explanation.

By the end of this article, you will be able to create some awesome data visualization using matplotlib and seaborn. So without further ado, let’s get started.

Brief about Data Visualization libraries we will be using

*Feel free to skip this part if you are already aware of these libraries…

Matplotlib: It is a plotting library for the Python programming language and it has numerical mathematics extension Numpy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, QT, WxPython, or GTX. (Source)

Seaborn: It is an amazing visualization library for statistical graphics plotting in python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on top of matplotlib library and is also closely integrated into the data structures from pandas. The aim of seaborn is to make visualization the central part of exploring and understanding data. It also provides dataset-oriented APIs so that we can switch between different visual representations for the same variables for a better understanding of the dataset. (Source)

Numpy: It is a library for python that supports multi-dimensional arrays and matrices with many high-level mathematical operations to perform on these arrays and matrices.

Pandas: It is a powerful, flexible, and easy-to-use data manipulation tool for the python programming language.

Best time to grab a Coffee !!

  Data pre-processing  Importing all the necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns Pre-processing the data



Calculating the missing data  for i in df.columns: null_rate = df[i].isna().sum()/len(df) * 100 print("{} null rate: {}%".format(i,round(null_rate,2))) director missing percentage: 30.68% cast missing percentage: 9.22% country missing percentage: 6.51% date_added missing percentage: 0.13% rating missing percentage: 0.09% Dealing with the missing data 

Here we will be replacing the missing country with the most country (mode), cast, and director with no data.

df['country'] = df['country'].fillna(df['country'].mode()[0]) df['cast'].replace(np.nan,'No data',inplace=True) df['director'].replace(np.nan,'No data',inplace=True) df.dropna(inplace=True) df.drop_duplicates(inplace=True)

Now we are done with missing values, but the dates are still not quite right…

df['date_added'] = pd.to_datetime(df['date_added']) df['month_added'] = df['date_added'].dt.month df['month_name_added'] = df['date_added'].dt.month_name() df['year_added'] = df['date_added'].dt.year Okay, let’s visualize now!!!

Netflix’s Brand Palette

Always use a color palette, it is a great way in achieving good integrity and helps us to give a professional look keeping all the readers engaged.

sns.palplot(['#221f1f', '#b20710', '#e50914','#f5f5f1']) plt.title("Netflix brand palette",loc='left',fontfamily='serif',fontsize=15,y=1.2) plt.show()

We will use Netflix brand colors wherever we can…

Let’s visualize the ratio between Netflix’s TV shows and Movies

Awesome !! Isn’t it?

Steps:

1. Calculating the ratio

x = df.groupby(['type'])['type'].count() y = len(df) r=((x/y)).round(2) mf_ratio = pd.DataFrame(r).T

Drawing the figure:

fig, ax = plt.subplots(1,1,figsize=(6.5,2.5)) ax.barh(mf_ratio.index, mf_ratio['Movie'], color='#b20710', alpha=0.9, label='Male') ax.barh(mf_ratio.index, mf_ratio['TV Show'], left=mf_ratio['Movie'], color='#221f1f', alpha=0.9, label='Female') ax.set_xlim(0, 1) ax.set_xticks([]) ax.set_yticks([]) plt.show()

2. Annotating the figure:

fig, ax = plt.subplots(1,1,figsize=(6.5,2.5)) ax.barh(mf_ratio.index, mf_ratio['Movie'], color='#b20710', alpha=0.9, label='Male') ax.barh(mf_ratio.index, mf_ratio['TV Show'], left=mf_ratio['Movie'], color='#221f1f', alpha=0.9, label='Female') ax.set_xlim(0, 1) ax.set_xticks([]) ax.set_yticks([]) for i in mf_ratio.index: ax.annotate(f"{int(mf_ratio['Movie'][i]*100)}%", xy=(mf_ratio['Movie'][i]/2, i), va = 'center', ha='center',fontsize=40, fontweight='light', fontfamily='serif', color='white') ax.annotate("Movie", xy=(mf_ratio['Movie'][i]/2, -0.25), va = 'center', ha='center',fontsize=15, fontweight='light', fontfamily='serif', color='white') for i in mf_ratio.index: ax.annotate(f"{int(mf_ratio['TV Show'][i]*100)}%", xy=(mf_ratio['Movie'][i]+mf_ratio['TV Show'][i]/2,i), va = 'center', ha='center',fontsize=40, fontweight='light', fontfamily='serif', color='white') ax.annotate("TV Shows", xy=(mf_ratio['Movie'][i]+mf_ratio['TV Show'][i]/2, -0.25), va = 'center', ha='center',fontsize=15, fontweight='light', fontfamily='serif', color='white') plt.show()

3. Adding text and removing legend & spines:

fig, ax = plt.subplots(1,1,figsize=(6.5,2.5)) ax.barh(mf_ratio.index, mf_ratio['Movie'], color='#b20710', alpha=0.9, label='Male') ax.barh(mf_ratio.index, mf_ratio['TV Show'], left=mf_ratio['Movie'], color='#221f1f', alpha=0.9, label='Female') ax.set_xlim(0, 1) ax.set_xticks([]) ax.set_yticks([]) for i in mf_ratio.index: ax.annotate(f"{int(mf_ratio['Movie'][i]*100)}%", xy=(mf_ratio['Movie'][i]/2, i), va = 'center', ha='center',fontsize=40, fontweight='light', fontfamily='serif', color='white') ax.annotate("Movie", xy=(mf_ratio['Movie'][i]/2, -0.25), va = 'center', ha='center',fontsize=15, fontweight='light', fontfamily='serif', color='white') for i in mf_ratio.index: ax.annotate(f"{int(mf_ratio['TV Show'][i]*100)}%", xy=(mf_ratio['Movie'][i]+mf_ratio['TV Show'][i]/2,i), va = 'center', ha='center',fontsize=40, fontweight='light', fontfamily='serif', color='white') ax.annotate("TV Shows", xy=(mf_ratio['Movie'][i]+mf_ratio['TV Show'][i]/2, -0.25), va = 'center', ha='center',fontsize=15, fontweight='light', fontfamily='serif', color='white') fig.text(0.125,1.0,'Movie & TV Show distribution',fontfamily='serif',fontsize=15,fontweight='bold') fig.text(0.125,0.90,'We see vastly more movies than TV shows on Netflix.',fontfamily='serif',fontsize=12,fontweight='light') for s in ['top','left','right','bottom']: ax.spines[s].set_visible(False) ax.legend().set_visible(False) plt.show()

Boom!!

Now let’s visualize Netflix’s Timeline

Steps:

1. Initializing the timeline list:

from datetime import datetime tl_dates = [ "1997nFounded", "1998nMail Services", "2003nGoes Public", "2007nStreming service", "2024nGoes Global", "2024nNetflix & Chill" ] tl_x = [1,2,4,5.3,8,9]

2. Drawing the figure :

fig,ax = plt.subplots(figsize=(15,4),constrained_layout=True) ax.set_ylim(-2,1.5) ax.set_xlim(0,10) ax.axhline(0, xmin=0.1, xmax=0.9,c="#000000",zorder=1) ax.scatter(tl_x,np.zeros(len(tl_x)),s=120,c="#4a4a4a",zorder=2) ax.scatter(tl_x, np.zeros(len(tl_x)), s=30, c='#fafafa', zorder=3) for x, date in zip(tl_x, tl_dates): ax.text(x, -0.55, date, ha='center', fontfamily='serif', fontweight='bold', color='#4a4a4a',fontsize=12) for spine in ["left", "top", "right", "bottom"]: ax.spines[spine].set_visible(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_title("Netflix through the years", fontweight="bold", fontfamily='serif', fontsize=16, color='#4a4a4a') plt.show()

Boom!!

Now let’s visualize histogram displaying countries

For that, we need to pre-process the data a little bit more:

Firstly, let’s print the country columns see what we get…

df['country']

As can we see that in 7782 and 7786 there are multi countries in a single column so what we will do is we will create another column that will store only the first country.

df['first_country'] = df['country'].apply(lambda x: x.split(",")[0]) df['first_country']

Now we will replace some of the country names with their short form.

df['first_country'].replace('United States', 'USA', inplace=True) df['first_country'].replace('United Kingdom', 'UK',inplace=True) df['first_country'].replace('South Korea', 'S. Korea',inplace=True)

After that, we calculate the total occurrence of each country.

df['count']=1 #helper column data = df.groupby('first_country')['count'].sum().sort_values(ascending=False)[:10]

output:

Now let’s get started with the visualization:

#Drawing the figure color_map = ['#f5f5f1' for _ in range(10)] color_map[0] = color_map[1]= color_map[2] = '#b20710' fig,ax = plt.subplots(1,1,figsize=(12,6)) #Annotating the figure ax.bar(data.index,data,width=0.5,edgecolor='darkgray',linewidth=0.6,color=color_map) for i in data.index: ax.annotate(f"{data[i]}",xy=(i,data[i]+100),va='center',ha='center',fontweight='light',fontfamily='serif') for s in ['top','left','right']: ax.spines[s].set_visible(False) #Adding text fig.text(0.125,1,'Top 10 countries on Netflix',fontsize=15,fontweight='bold',fontfamily='serif') fig.text(0.125,0.95,'The three most frequent countries have been highlighted.',fontsize=10,fontweight='light',fontfamily='serif') fig.text(1.1, 1.01, 'Insight', fontsize=15, fontweight='bold', fontfamily='serif') fig.text(1.1, 0.67, ''' Here we see that US is major content producers for Netflix, and on second we have India after UK and so on. Netflix being a US Company, it makes sense that they major producers. ''' , fontsize=12, fontweight='light', fontfamily='serif') ax.grid(axis='y', linestyle='-', alpha=0.5)

At last, we will create a word cloud:

To create a word cloud you will be needing a mask(Structure of our word cloud) in this example mask image is given below, feel free to create any shape you want.

Importing necessary libraries:

from wordcloud import WordCloud import random from PIL import Image import matplotlib

Creating a word cloud and displaying it:

paintcmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ['#221f1f', '#b20710']) text = str(list(df['title'])).replace(',', '').replace('[', '').replace("'", '').replace(']', '').replace('.', '') mask = np.array(Image.open('mask.png')) wordcloud = WordCloud(background_color = 'white', width = 500, height = 200,colormap=cmap, max_words = 150, mask = mask).generate(text) plt.figure( figsize=(5,5)) plt.imshow(wordcloud, interpolation = 'bilinear') plt.axis('off') plt.tight_layout(pad=0) plt.show()   Keep in Mind

Always make sure that you keep your data visualizations organized and Coherent.

Make sure to use proper colours to represent and differentiate information. Colours can be a key factor in a reader’s decisions.

Use high contrast colours and annotate the elements of your data visualization properly.

Never distort the data, data visualization is said to be great when it tells the story clearly without distortions.

Never use a graphical representation that does not represent the data set accurately(For eg: 3D pie charts).

Your Data visualization should be easy to comprehend at a glance.

Never forget that our agenda of data visualization is to enhance the data with the help of design, not just draw attention to the design itself.

Conclusion

So, we wrap up our first tutorial on Netflix Data visualization – Part 1 here. There is still a problem with this visualization i.e. these are not interactive, the ones we can build with plotly and cufflinks.

Sometimes data visualization should be captivating and attention-grabbing which I think we have achieved here even if it isn’t precise. So by customizing our visualization like what we did here reader’s eye is drawn exactly where we want.

Connect me on LinkedIn

Email: [email protected]

Thank You !!

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Related

A Comprehensive Guide To Using Snap Packages On Ubuntu

What are Snap Packages?

Snap packages are self-contained, containerized applications that run in a sandboxed environment. They are designed to work across different Linux distributions and provide an easy way to install and manage software on Ubuntu. Snap packages are created using Snapcraft tool, which allows developers to package their applications and their dependencies into a single file. This makes it easy to distribute and install software on Ubuntu.

Installing Snapd

To use snap packages on Ubuntu, you need to have snapd installed. Snapd is daemon that manages snap packages. To install snapd, open terminal and type following command −

sudo apt install snapd Installing Snap Packages

To install a snap package, you can use snap command followed by name of package. For example, to install Firefox snap package, you can use following command −

sudo snap install firefox

This will download and install Firefox snap package. Once installation is complete, you can launch Firefox from Applications menu or by typing firefox in terminal.

Managing Snap Packages

Snap packages can be managed using snap command. following are some of most commonly used snap commands −

snap find − This command allows you to search for snap packages in Snap Store.

snap install − This command allows you to install a snap package.

snap remove − This command allows you to remove a snap package.

snap refresh − This command allows you to update a snap package to latest version.

snap list − This command allows you to list all installed snap packages.

For example, to search for a package in Snap Store, you can use following command −

snap find package_name

To remove a package, you can use following command −

sudo snap remove package_name sudo snap remove package_name

Snap packages are automatically updated by default. However, you can also manually update snap packages using snap command. To update a snap package, you can use following command −

sudo snap refresh package_name

This will update package to latest version.

Snap Package Configuration

Snap packages are designed to run in a sandboxed environment, which means they have limited access to system resources. However, you can configure snap packages to have access to certain system resources using snap interfaces.

Snap interfaces are predefined sets of permissions that allow snap packages to access system resources such as network, USB devices, and sound devices. You can view available snap interfaces using following command −

snap interfaces

To connect a snap package to a specific interface, you can use following command −

sudo snap connect package_name:interface_name

For example, to give Firefox snap package access to network, you can use following command −

sudo snap connect firefox:network Version Control

Snap packages provide version control, which means you can install multiple versions of same package and switch between them as needed. This is particularly useful for developers who need to test their applications on different versions of dependencies.

Dependency Management

Snap packages include all necessary dependencies, which means you don’t have to worry about installing and managing dependencies separately. This is particularly useful for complex applications with many dependencies.

Easy Rollback

Snap packages provide easy rollback, which means you can easily revert to a previous version of a package if there are any issues with latest version. This is particularly useful for system administrators who need to ensure system stability.

Security

Snap packages run in a sandboxed environment, which means they have limited access to system resources. This provides an additional layer of security and helps to prevent malicious applications from accessing sensitive system resources.

Cross-Distribution Compatibility

Snap packages are designed to work across different Linux distributions, which means you can distribute your applications to users on other distributions without having to worry about compatibility issues.

Automatic Updates

Snap packages are automatically updated by default, which means you always have latest version of software. This helps to ensure that your applications are up-to-date and secure.

Easy Distribution

Snap packages are easy to distribute, as they can be uploaded to Snap Store and made available to millions of Ubuntu users. This provides a centralized and easy way to distribute software.

Snap packages are also great for system administrators, as they provide a centralized and easy way to manage software on multiple machines. You can create a custom image with all necessary snap packages pre-installed and deploy it to multiple machines.

Conclusion

Overall, snap packages are a great addition to Ubuntu ecosystem and provide a modern way to package and distribute software. They are easy to use, secure, and provide automatic updates, making them a great choice for both end-users and developers.

Template Matching Using Opencv In Python

The Template matching is a technique, by which a patch or template can be matched from an actual image. This is basically a pattern matching mechanism.

In Python there is OpenCV module. Using openCV, we can easily find the match. So in this problem, the OpenVC template matching techniques are used.

To use the OpenCV functionality, we need to download them using pip.

sudo pip3 install opencv-python

For template matching task, there is an accuracy factor, this factor is known as threshold. As an example, we can say that we can easily create face recognizing scheme using this template matching solution. We can provide some images of eyes or any other parts of faces, then using those images as template, it can easily find the match, but there are different variations in eyes. So if we set the accuracy level to 50%, it will detect better than accuracy level 100%.Generally, the accuracy level is 80% in different cases.

Steps to match Templates

Take the actual image and convert it into a gray scale image.

Take template as gray scale image

The template slides over the actual image and find the location where accuracy level matches.

When result is greater than the accuracy level, mark that position as detected.

For the first case the Input image and the template is −

Main Image The template Example code import cv2 import numpy as np #open the main image and convert it to gray scale image main_image = cv2.imread('main_image.png') gray_image = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY) #open the template as gray scale image template = cv2.imread('template1.png', 0) width, height = template.shape[::-1] #get the width and height #match the template using cv2.matchTemplate match = cv2.matchTemplate(gray_image, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 for point in zip(*position[::-1]): #draw the rectangle around the matched template cv2.rectangle(main_image, point, (point[0] + width, point[1] + height), (0, 204, 153), 0) cv2.imshow('Template Found', main_image) cv2.waitKey(0) Output

The above code does not support multi-scaling. So if the size of the template is not same, it will not detect. So in the next part, we will see how we can use the multi-scaling feature to detect templates.

In this approach, the actual image is converted into different sizes, each time it matches the pattern, and finds the largest correlation coefficient to locate the matches.

Here the actual image is same, the template is here −

Example code import imutils import cv2 import numpy as np #Open template and get canny template = cv2.imread('template3.jpg') template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) template = cv2.Canny(template, 10, 25) (height, width) = template.shape[:2] #open the main image and convert it to gray scale image main_image = cv2.imread('main_image.png') gray_image = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY) temp_found = None for scale in np.linspace(0.2, 1.0, 20)[::-1]: #resize the image and store the ratio resized_img = imutils.resize(gray_image, width = int(gray_image.shape[1] * scale)) ratio = gray_image.shape[1] / float(resized_img.shape[1]) if resized_img.shape[0] < height or resized_img.shape[1] < width: break #Convert to edged image for checking e = cv2.Canny(resized_img, 10, 25) match = cv2.matchTemplate(e, template, cv2.TM_CCOEFF) (_, val_max, _, loc_max) = cv2.minMaxLoc(match) temp_found = (val_max, loc_max, ratio) #Get information from temp_found to compute x,y coordinate (_, loc_max, r) = temp_found (x_start, y_start) = (int(loc_max[0]), int(loc_max[1])) (x_end, y_end) = (int((loc_max[0] + width)), int((loc_max[1] + height))) #Draw rectangle around the template cv2.rectangle(main_image, (x_start, y_start), (x_end, y_end), (153, 22, 0), 5) cv2.imshow('Template Found', main_image) cv2.waitKey(0) Output

Calculating Profit Or Loss Using Python

In this article, we will learn a Python Program to calculate Profit Or Loss.

The following are the different methods to accomplish this task −

Using If Conditional Statements

Using the abs() function.

What are the selling price, cost price, and Profit and Loss?

The price a consumer pays to purchase a product or a commodity is known as the selling price. It is a price that is higher than the cost price and also includes a portion of the profit.

Cost price is the cost at which the seller buys the product or the commodity. He follows that by adding a portion of gain or profits.

The amount gained from selling an item for more than its cost price is known as the profit.

Profit = Selling Price – Cost Price.

Loss is the amount lost by selling an item for less than its cost price.

Loss = Cost Price - Selling Price Method 1: Using If Conditional Statements

Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

Create a function to calculate Profit that accepts the cost price(cp) and selling price(sp) as arguments.

Use the mathematical formula sp – cp to calculate profit and create a variable to store it.

Return the above-calculated profit using the return keyword.

Create another function to calculate Loss that accepts the cost price(cp) and selling price(sp) as arguments.

Use the mathematical formula cp – sp to calculate loss and create a variable to store it.

Return the above-calculated loss using the return keyword.

Create two separate variables to store the input cost price and selling price.

Use the if conditional statement and ‘==’ operator to check whether the input selling price is equal to the cost price.

Print Neither profit nor Loss if the condition is true.

Use the elif conditional statement to check whether the selling price is greater than the cost price.

Print profit if the condition is true by calling calculateProfit function by passing cost price and selling price as arguments to get the profit value.

Else print Loss by calling calculateLoss function by passing cost price and selling price as arguments to it to get the loss value.

Example

The following program calculates the profit or loss using the if conditional statements −

# creating a function to calculate Profit that # accepts the cost price(cp) and selling price(sp) as arguments def calculateProfit(cp, sp): # formula for calculating profit resultProfit = (sp - cp) # returning the resulting profit return resultProfit # creating a function to calculate Loss that # accepts the cost price(cp) and selling price(sp) as arguments def calculateLoss(cp, sp): # formula for calculating loss resultLoss = (cp - sp) # returning the resultant loss. return resultLoss # input cost price cost_price = 500 # input selling price selling_price = 1000 # checking whether the selling price is equal to the cost price if selling_price == cost_price: # printing Neither profit nor loss if the condition is true print("Neither profit nor Loss") # checking whether the selling price is greater than the cost price # Calling calculateProfit function by passing cost price and selling price # as arguments and printing profit if the condition is true print("The Profit is", calculateProfit(cost_price, selling_price)) else: # Else calling calculateLoss function by passing cost price and # selling price as arguments and printing Loss print("The Loss is", calculateLoss(cost_price, selling_price)) Output

On execution, the above program will generate the following output −

The Profit is 500 Method 2: Using the abs() function Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

Create a function to calculate the difference between the selling price and cost price that accepts the cost price(cp) and selling price(sp) as arguments.

Use the abs() function to calculate the difference between the selling price and the cost price.

Return the difference between the selling price and the cost price.

Create two separate variables to store the input cost price and selling price.

Print the profit/loss like the previous method.

Example

The following program calculates the profit or loss using the abs() function −

# creating a function to calculate the difference between sp and cp that # accepts the cost price(cp) and selling price(sp) as arguments def calculateDifference(cp, sp): # calculating the difference between the selling price and the cost price difference = abs(sp - cp) # returning the absolute difference of selling and cost price return difference # input cost price cost_price = 500 # input selling price selling_price = 1000 # checking whether the selling price is equal to the cost price if selling_price == cost_price: # printing Neither profit nor Loss if the condition is true print("Neither profit nor Loss") # checking whether the selling price is greater than the cost price # printing profit if the condition is true, by calling calculateDifference # function by passing cost price and selling price as arguments print("The Profit is", calculateDifference(cost_price,selling_price)) # Else this is the case of loss else: # Else printing Loss if the condition is true by calling calculateDifference # function by passing cost price and selling price as arguments to it print("The Loss is", calculateDifference(cost_price,selling_price)) Output

On execution, the above program will generate the following output −

The Loss is 200 Conclusion

In this article, we learned what selling and cost prices are as well as how to create a Python program to determine profit or loss when selling and cost prices are given. As an alternative to using two different functions, we learned how to calculate the absolute difference between selling and cost prices using the abs() function.

Update the detailed information about Full Guide On Whatsapp Automation Using Python on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!