Big Book of Python Scripts
Big Book of Python Scripts
Ryan Wells
wellsr.com
Table of Contents
Contents
Introduction: Getting Started with Python ........................................................................................................... 5
Python Data Types ............................................................................................................................................ 6
Python Data Structures...................................................................................................................................... 7
Using Python Functions and Defining New Functions ........................................................................................ 8
Creating and Using Python Class Objects and Iterators .................................................................................... 9
Python I/O: Input and Output Examples and Tools .......................................................................................... 10
Python String Operations and String Formatting .............................................................................................. 11
Pandas DataFrame from Dictionary, List, and List of Dicts .............................................................................. 12
Pandas read_csv Examples for Importing Files ............................................................................................... 13
Python with Pandas: Comparing Two DataFrames .......................................................................................... 14
Python with Pandas: Convert String to Float and other Numeric Types ........................................................... 15
Using Pandas Concat to Merge DataFrames................................................................................................... 16
Create Histograms from Pandas DataFrames ................................................................................................. 17
Create Pandas Density Plots from DataFrames............................................................................................... 18
Create Pandas Boxplots with DataFrames ...................................................................................................... 19
Python Comprehension and Generator Expressions ....................................................................................... 20
Reading CSV Files with the Python CSV Module ............................................................................................ 21
Writing CSV Files with the Python CSV Module .............................................................................................. 23
How to Add and Read Database Data with Python sqlite3............................................................................... 24
Copy Data from Excel to an sqlite3 Database with Python .............................................................................. 25
Adapting and Converting SQLite Data Types for Python ................................................................................. 26
Understanding Python Regex Matching........................................................................................................... 27
Using Python Regex Groups to Capture Substrings ........................................................................................ 28
Grouping DataFrame Data with the Pandas groupby Operation ...................................................................... 29
Using Command Line Arguments with Python sys.argv ................................................................................... 30
Using Python stdin, stdout, and stderr with the sys Module ............................................................................. 31
Create a Python Voronoi Diagram with GeoPandas and Geoplot .................................................................... 32
Creating Interactive Python Choropleth Maps with Plotly ................................................................................. 33
Introduction to Seaborn Plots for Python Data Visualization ............................................................................ 34
Seaborn Barplot Tutorial for Python ................................................................................................................. 35
Seaborn Line Plot Data Visualization ............................................................................................................... 36
How to Make Seaborn Boxplots in Python ....................................................................................................... 37
The Basics of NumPy Arrays and How to Use Them ....................................................................................... 38
Page 2 of 93 wellsr.com
Table of Contents
Transposing a Matrix with Numpy .................................................................................................................... 39
Python Sentiment Analysis with scikit-learn ..................................................................................................... 40
Making Seaborn Scatter Plots with sns.scatterplot .......................................................................................... 42
Solving a System of Linear Equations with Python's NumPy ........................................................................... 43
Using Python TensorFlow 2.0 for Classification Tasks..................................................................................... 44
Using Python TensorFlow 2.0 for Regression Tasks ....................................................................................... 45
Seaborn Histogram DistPlot Tutorial for Python ............................................................................................... 47
Python Machine Learning Examples with scikit-learn ...................................................................................... 48
Joining DataFrames with Python Pandas Join ................................................................................................. 49
Using Pandas Apply on Dataframes and Series .............................................................................................. 50
Python Default Arguments and Function Overloading ..................................................................................... 51
Python Lemmatization with NLTK .................................................................................................................... 52
How to Perform Python NLTK Tokenization..................................................................................................... 53
Remove Stop Words with Python NLTK .......................................................................................................... 54
Stemming in Python with NLTK Examples ....................................................................................................... 55
Python Named Entity Recognition with NLTK & spaCy .................................................................................... 56
Understanding Inheritance in Python with Examples ....................................................................................... 57
Performing CRUD operations with Python and MySQL ................................................................................... 58
Web Scraping with Python Scrapy ................................................................................................................... 60
Python Speech Recognition and Audio Transcription ...................................................................................... 61
14 Examples To Help You Understand Python List Slicing .............................................................................. 62
Zipping and Unzipping Files and Folders with Python ...................................................................................... 63
Sending Emails through Gmail with Python ..................................................................................................... 64
Read Gmail Emails With Python ...................................................................................................................... 65
Python Machine Learning for Spam Email Detection ....................................................................................... 66
How to Extend Functions with Python Decorators ........................................................................................... 68
Python unittest Examples for Testing Python Code ......................................................................................... 69
Multithreading in Python: Running Functions in Parallel .................................................................................. 70
3 Ways to Calculate Python Execution Time ................................................................................................... 71
Understanding Python if __name__ == '__main__' statements........................................................................ 72
How to Read PDF Files with Python using PyPDF2 ........................................................................................ 73
How to use the Python pdb debugger .............................................................................................................. 74
Python Face Detection for Beginners with OpenCV ......................................................................................... 75
Convert Image to String with Python Pytesseract OCR ................................................................................... 76
Python Image Manipulation with Pillow Library ................................................................................................ 77
Page 3 of 93 wellsr.com
Table of Contents
Drawing Shapes on Images with the Python OpenCV Library ......................................................................... 78
Python chdir and getcwd to Set Working Directory .......................................................................................... 79
List Files in a Folder With Python OS listdir and walk ...................................................................................... 80
How to Open Files with Python OS .................................................................................................................. 81
Python OS Delete Files and Create Folders .................................................................................................... 82
Logging Info and Errors with the Python Logging Module ................................................................................ 83
Random Number Generation in Python with Random Module ......................................................................... 84
Python Delete All Files in a Folder ................................................................................................................... 85
Python Map, Filter and Reduce for Lambda Functions .................................................................................... 86
Sorting items in Python using Sort and Sorted Methods .................................................................................. 87
NumPy Eigenvalues and Eigenvectors with Python ......................................................................................... 88
Outer Product of Two Vectors or Matrices with Python NumPy ....................................................................... 89
Python k-means clustering with scikit-learn ..................................................................................................... 90
Asynchronous Programming in Python with Asyncio ....................................................................................... 91
Python Agglomerative Clustering with sklearn ................................................................................................. 92
Python PCA Examples with sklearn ................................................................................................................. 93
Page 4 of 93 wellsr.com
Introduction: Getting Started with Python
More Info
while True: # This is an infinite loop. We will cover loops in a future tutorial
x = 0
# Ctrl + c
> KeyboardInterrupt
Page 5 of 93 wellsr.com
Python Data Types
More Info
print(int("409"))
> 409
x = ("Student " + "\t" + "Country " + "\t" + "GDP (billion USD)" + "\t" "Population" + "\t" "In Africa?" +
"\n"
+"Mary " + "\t" + "Luxembourg" + "\t" + "64.2 " + "\t" "602005 " + "\t" "False" + "\n"
+"Matthew " + "\t" + "Eritrea " + "\t" + "6.856 " + "\t" "4954645 " + "\t" "True" + "\n"
+"Marie " + "\t" + "None " + "\t" + "None " + "\t" "None " + "\t" "None" + "\n"
+"Manuel " + "\t" + "Lesotho " + "\t" + "2.721 " + "\t" "2203821 " + "\t" "True" + "\n"
+"Malala " + "\t" + "Poland " + "\t" + "614.190 " + "\t" "38433600 " + "\t" "False" +
"\n" )
print(x)
> Student Country GDP (billion USD) Population In Africa?
> Mary Luxembourg 64.2 602005 False
> Matthew Eritrea 6.856 4954645 True
> Marie None None None None
> Manuel Lesotho 2.721 2203821 True
> Malala Poland 614.190 38433600 False
Page 6 of 93 wellsr.com
Python Data Structures
More Info
# Python Dictionaries
d = {"a":1, "b":2, "c":3, "d":4}
d
> {'a': 1, 'b': 2, 'c': 3, 'd': 4}
type(d)
> dict
d["c"]
> 3
# Python Sets
s = {1, 2.3, "apple", False, None}
s
> {1, 2.3, False, None, 'apple'}
type(s)
> set
# Python Tuples
t = 1, 2, 3, 4, 5, 6
t
> (1, 2, 3, 4, 5, 6)
type(t)
> tuple
t = 1, 2, 3, 4, 5, 6
t[2]
> 3
t[2:5]
> (3, 4, 5)
Page 7 of 93 wellsr.com
Using Python Functions and Defining New Functions
More Info
Page 8 of 93 wellsr.com
Creating and Using Python Class Objects and Iterators
More Info
Page 9 of 93 wellsr.com
Python I/O: Input and Output Examples and Tools
More Info
Page 10 of 93 wellsr.com
Python String Operations and String Formatting
More Info
n = 42.2222222222222
m = -22.0
s = "The secret number is {:07.2f}, not {:07.2f}".format(n, m) # Pad with 0's, force length of 7, with 2
decimals of precision for floating point
print(s)
> The secret number is 0042.22, not -022.00
s = "The secret number is {:.2e}, not {:.2E}".format(n, m) # Use 2 decimals of precision, in two types of
scientific notation
print(s)
> The secret number is 4.22e+01, not -2.20E+01
Page 11 of 93 wellsr.com
Pandas DataFrame from Dictionary, List, and List of Dicts
More Info
Page 12 of 93 wellsr.com
Pandas read_csv Examples for Importing Files
More Info
Page 13 of 93 wellsr.com
Python with Pandas: Comparing Two DataFrames
More Info
Page 14 of 93 wellsr.com
Python with Pandas: Convert String to Float and other
Numeric Types
More Info
Python with Pandas: Convert String to Float and other Numeric Types
This tutorial will show you how to convert Pandas DataFrame strings into floats or ints. Converting
Pandas string data to numeric types is required before performing numeric calculations.
import pandas as pd
import numpy as np # To use the int64 dtype, we will need to import numpy
grades["StudentID"] = grades["StudentID"].astype(dtype=np.int64)
grades.info()
> <class 'pandas.core.frame.DataFrame'>
> RangeIndex: 4 entries, 0 to 3
> Data columns (total 5 columns):
> StudentID 4 non-null int64
> Homework 4 non-null object
> Midterm 4 non-null object
> Project 4 non-null object
> Final 4 non-null object
> dtypes: int64(1), object(4)
> memory usage: 240.0+ bytes
Page 15 of 93 wellsr.com
Using Pandas Concat to Merge DataFrames
More Info
Page 16 of 93 wellsr.com
Create Histograms from Pandas DataFrames
More Info
Page 17 of 93 wellsr.com
Create Pandas Density Plots from DataFrames
More Info
Page 18 of 93 wellsr.com
Create Pandas Boxplots with DataFrames
More Info
Page 19 of 93 wellsr.com
Python Comprehension and Generator Expressions
More Info
Page 20 of 93 wellsr.com
Reading CSV Files with the Python CSV Module
More Info
def handle_system_error(error):
""" Handler for I/O errors. """
print("System error: %s" % traceback.format_exc())
def handle_decoding_error(error):
""" Handler for decoding strings with UTF-8. """
print("Decoding error: %s" % traceback.format_exc())
def handle_other_errors(error):
""" Catch-all handler. """
print("Extrema ratio.")
sys.exit(1)
def convert_row(row):
""" Convert a CSV record in a list of Python objects. """
return row
def finalize_rows(rows):
""" Perform some operations on rows before exiting. """
return rows
try:
with open(path, 'rt', encoding='utf-8') as src:
reader = csv.reader(src, strict=True)
for row in reader:
rows.append(convert_row(row))
except EnvironmentError as error:
handle_system_error(error)
except UnicodeDecodeError as error:
handle_decoding_error(error)
except csv.Error as error:
handle_reader_error(error, reader)
except:
handle_other_errors(error)
else:
rows = finalize_rows(rows)
return rows
Page 21 of 93 wellsr.com
Reading CSV Files with the Python CSV Module
More Info
def test_exception():
""" Raising different kind of exceptionss. """
# Wrong file path
process_csv_data('nowhere.csv')
# Decoding error
process_csv_data('decode.csv')
# Reader error
process_csv_data('faulty-sample.csv')
Page 22 of 93 wellsr.com
Writing CSV Files with the Python CSV Module
More Info
def write_to_csv_file():
""" Write all album released after 2014 to a CSV file. """
with sqlite3.connect('sample.db3') as connection, open(
'albums.csv', 'w', encoding='utf-8', newline='') as dump:
cursor = connection.cursor()
writer = csv.writer(dump)
Page 23 of 93 wellsr.com
How to Add and Read Database Data with Python sqlite3
More Info
Page 24 of 93 wellsr.com
Copy Data from Excel to an sqlite3 Database with Python
More Info
def case_study_3():
""" Test for case study 3. """
with ExcelDocument('pivot.xls') as src:
table = pandas.pivot_table(
src['pivot-data'].data_frame(),
columns = 'month',
values = 'income',
index = 'seller',
aggfunc = {'income' : sum},
fill_value = 0 )
print(table)
Page 25 of 93 wellsr.com
Adapting and Converting SQLite Data Types for Python
More Info
def test_date_by_colnames():
""" Match default date converters by column names. """
with sqlite3.connect(
':memory:',
detect_types=sqlite3.PARSE_COLNAMES) as conn:
date, type_1, timestamp, type_2 = conn.execute(
'SELECT CURRENT_DATE AS "d [date]", typeof(CURRENT_DATE), ' \
'CURRENT_TIMESTAMP AS "ts [timestamp]", ' \
'typeof(CURRENT_TIMESTAMP);').fetchone()
print('current date is %s (from %s to %s)\n' \
'current timestamp is %s (from %s to %s)\n' \
% (date, type_1.upper(), type(date),
timestamp, type_2.upper(), type(timestamp)))
test_date_by_colnames()
Page 26 of 93 wellsr.com
Understanding Python Regex Matching
More Info
def test_nonsense_repetitions():
""" Nonsense uses of the repetition operator. """
# Omitting both parameters, but without comma
print(re.match('a{}' , 'a{}').group() == 'a{}')
# Non-numeric parameters for the repetition operator
print(re.match('a{x,y}' , 'a{x,y}').group() == 'a{x,y}')
# Space within the repetition operator
print(re.match('a{1, 2}', 'a{1, 2}').group() == 'a{1, 2}')
# Space are not allowed even in VERBOSE mode
print(re.match('a{1, 2}', 'a{1,2}',
re.VERBOSE).group() == 'a{1,2}')
# Lower bound is greater than the upper bound
try:
re.match('a{4,2}', 'aa').group()
except re.error as err:
print(err)
test_nonsense_repetitions()
Page 27 of 93 wellsr.com
Using Python Regex Groups to Capture Substrings
More Info
def test_match_tags():
""" Matching HTML tags. """
sample = r'''
<b>Bold</b><i>Italics</i>
<mod>Mod</mod><em>Emphasis</em>
<h2>Level 2 Header</h2>
<code>Bad code match</cod>
<h1>Bad header match</h3>
'''
regex_noref = re.compile(r'''
<(?P<otag>\w+)> # opening tag
(?P<text>[^<]*) # contents
</(?P<ctag>\w+)> # closing tag
''', re.VERBOSE)
regex = re.compile(r'''
<(?P<otag>\w+)> # opening tag
(?P<text>[^<]*) # contents
</(?P<ctag>(?P=otag))> # closing tag
''', re.VERBOSE)
test_match_tags()
Page 28 of 93 wellsr.com
Grouping DataFrame Data with the Pandas groupby
Operation
More Info
Page 29 of 93 wellsr.com
Using Command Line Arguments with Python sys.argv
More Info
Page 30 of 93 wellsr.com
Using Python stdin, stdout, and stderr with the sys Module
More Info
Using Python stdin, stdout, and stderr with the sys Module
This tutorial will explain how to use shell standard input (stdin), standard output (stdout), and standard
error (stderr) in Python programs using the sys module.
import sys
for line in sys.stdin:
print(line + "to stdout")
print(line + "to sterr", file=sys.stderr)
Page 31 of 93 wellsr.com
Create a Python Voronoi Diagram with GeoPandas and
Geoplot
More Info
Page 32 of 93 wellsr.com
Creating Interactive Python Choropleth Maps with Plotly
More Info
Page 33 of 93 wellsr.com
Introduction to Seaborn Plots for Python Data Visualization
More Info
Page 34 of 93 wellsr.com
Seaborn Barplot Tutorial for Python
More Info
Page 35 of 93 wellsr.com
Seaborn Line Plot Data Visualization
More Info
Page 36 of 93 wellsr.com
How to Make Seaborn Boxplots in Python
More Info
Page 37 of 93 wellsr.com
The Basics of NumPy Arrays and How to Use Them
More Info
Page 38 of 93 wellsr.com
Transposing a Matrix with Numpy
More Info
M2T = np.transpose(M2)
print(f'Transposed Matrix:\n{M2T}')
print("Shape of the transposed matrix ", np.array(M2T).shape)
Page 39 of 93 wellsr.com
Python Sentiment Analysis with scikit-learn
More Info
plt.rcParams["figure.figsize"] = [10, 8]
imdb_reviews.Sentiment.value_counts().plot(kind='pie', autopct='%1.0f%%')
reviews = imdb_reviews["SentimentText"].tolist()
labels = imdb_reviews["Sentiment"].values
processed_reviews = []
processed_reviews.append(text)
print(confusion_matrix(y_test,y_pred))
Page 40 of 93 wellsr.com
Python Sentiment Analysis with scikit-learn
More Info
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
Page 41 of 93 wellsr.com
Making Seaborn Scatter Plots with sns.scatterplot
More Info
Page 42 of 93 wellsr.com
Solving a System of Linear Equations with Python's NumPy
More Info
B = np.array([102, 110])
X = np.linalg.solve(A,B)
print(X)
Page 43 of 93 wellsr.com
Using Python TensorFlow 2.0 for Classification Tasks
More Info
dataset = sns.load_dataset('iris')
dataset.head()
X = dataset.drop(['species'], axis=1)
y = pd.get_dummies(dataset.species, prefix='output')
X.head()
y.head()
X = X.values
y = y.values
input_1 = Input(shape=(X_train.shape[1],))
l1 = Dense(100, activation='relu')(input_1)
l2 = Dense(50, activation='relu')(l1)
l3 = Dense(25, activation='relu')(l2)
output_1 = Dense(y_train.shape[1], activation='softmax')(l3)
print(model.summary())
Page 44 of 93 wellsr.com
Using Python TensorFlow 2.0 for Regression Tasks
More Info
tf.__version__
reg_dataset = sns.load_dataset('diamonds')
reg_dataset.head()
reg_dataset.shape
reg_dataset.describe()
list(reg_dataset.cut.unique())
cut_onehot = pd.get_dummies(reg_dataset.cut).iloc[:,1:]
color_onehot = pd.get_dummies(reg_dataset.color).iloc[:,1:]
clarity_onehot = pd.get_dummies(reg_dataset.clarity).iloc[:,1:]
cut_onehot.head()
reg_dataset.head()
labels = reg_dataset['price'].values
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
input_layer = Input(shape=(features.shape[1],))
l1 = Dense(100, activation='relu')(input_layer)
l2 = Dense(50, activation='relu')(l1)
l3 = Dense(25, activation='relu')(l2)
output = Dense(1)(l3)
Page 45 of 93 wellsr.com
Using Python TensorFlow 2.0 for Regression Tasks
More Info
print(model.summary())
pred_train = model.predict(X_train)
print(mean_absolute_error(y_train,pred_train))
pred = model.predict(X_test)
print(mean_absolute_error(y_test,pred))
Page 46 of 93 wellsr.com
Seaborn Histogram DistPlot Tutorial for Python
More Info
Page 47 of 93 wellsr.com
Python Machine Learning Examples with scikit-learn
More Info
Page 48 of 93 wellsr.com
Joining DataFrames with Python Pandas Join
More Info
Page 49 of 93 wellsr.com
Using Pandas Apply on Dataframes and Series
More Info
Page 50 of 93 wellsr.com
Python Default Arguments and Function Overloading
More Info
Page 51 of 93 wellsr.com
Python Lemmatization with NLTK
More Info
Page 52 of 93 wellsr.com
How to Perform Python NLTK Tokenization
More Info
Page 53 of 93 wellsr.com
Remove Stop Words with Python NLTK
More Info
Page 54 of 93 wellsr.com
Stemming in Python with NLTK Examples
More Info
tokens = nltk.word_tokenize(sentence )
sb_stem =SnowballStemmer("english")
for token in tokens :
stem = sb_stem.stem(token)
print(token, "=>", stem)
Page 55 of 93 wellsr.com
Python Named Entity Recognition with NLTK & spaCy
More Info
sentence = """Born and raised in Madeira, Ronaldo began his senior club career playing for Sporting CP,
before signing with Manchester United in 2003, aged 18. After winning the FA Cup in his first season,
he helped United win three successive Premier League titles, the UEFA Champions League, and the FIFA Club World
Cup"""
entity_doc = spacy_model(sentence)
entity_doc.ents
Page 56 of 93 wellsr.com
Understanding Inheritance in Python with Examples
More Info
class Y:
def methodB(self):
print("This is method B of class Y")
class Z(X,Y):
def methodC(self):
print("This is method C of child class Z")
Page 57 of 93 wellsr.com
Performing CRUD operations with Python and MySQL
More Info
host_name = "localhost"
user_name = "root"
password = ""
my_con = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=password
)
cursor = my_con.cursor()
query = "CREATE DATABASE patient_db"
cursor.execute(query)
my_db_con = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=password,
database=db_name
)
create_table_query = """
CREATE TABLE IF NOT EXISTS patients (
id INT AUTO_INCREMENT,
name TEXT NOT NULL,
age INT,
sex TEXT,
PRIMARY KEY (id)
) ENGINE = InnoDB
"""
cursor = my_db_con.cursor()
cursor.execute(create_table_query)
my_db_con.commit()
Page 58 of 93 wellsr.com
Performing CRUD operations with Python and MySQL
More Info
# Inserting Records in a Table
create_patients_query = """
INSERT INTO
`patients` (`name`, `age`, `sex`)
VALUES
('Laura', 24, 'female'),
('Jospeh', 41, 'male'),
('Angel', 33, 'female'),
('Elisabeth', 37, 'female'),
('Joel', 19, 'male');
"""
cursor = my_db_con.cursor()
cursor.execute(create_patients_query)
my_db_con.commit()
patients = cursor.fetchall()
update_patients_query = """
UPDATE
patients
SET
sex = 'f'
WHERE
sex = 'female'
"""
cursor.execute(update_patients_query)
my_db_con.commit()
cursor.execute(delete_patients_query)
my_db_con.commit()
Page 59 of 93 wellsr.com
Web Scraping with Python Scrapy
More Info
class ImdbSpiderSpider(scrapy.Spider):
name = 'imdb_spider'
allowed_domains = ['imdb.com']
start_urls = ["https://www.imdb.com/search/title/?groups=top_250"]
movies = response.xpath("//div[@class='lister-item-content']")
yield{
'movie name':movie_name,
'movie link':movie_link,
'movie_rating':movie_rating
}
Page 60 of 93 wellsr.com
Python Speech Recognition and Audio Transcription
More Info
recognizer.adjust_for_ambient_noise(file_audio)
print( recognizer.recognize_google(file_audio))
Page 61 of 93 wellsr.com
14 Examples To Help You Understand Python List Slicing
More Info
Page 62 of 93 wellsr.com
Zipping and Unzipping Files and Folders with Python
More Info
Page 63 of 93 wellsr.com
Sending Emails through Gmail with Python
More Info
Page 64 of 93 wellsr.com
Read Gmail Emails With Python
More Info
Page 65 of 93 wellsr.com
Python Machine Learning for Spam Email Detection
More Info
%matplotlib inline #comment this line out if not using Jupyter notebook
dataset = pd.read_csv(r"C:\Datasets\email_dataset.csv")
dataset.head(10)
print("Data Visualization")
dataset.shape
dataset.spam.value_counts()
sns.countplot(x='spam', data=dataset)
print("Data Preprocessing")
messages = dataset["text"].tolist()
output_labels = dataset["spam"].values
import re
processed_messages = []
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
Page 66 of 93 wellsr.com
Python Machine Learning for Spam Email Detection
More Info
Page 67 of 93 wellsr.com
How to Extend Functions with Python Decorators
More Info
def wrapper_function():
print("This is some code before the decorated function")
function_to_be_decorated()
return wrapper_function
@my_decorator
def my_func():
print("This is the function to be decorated")
@my_decorator
def my_func2():
print("This is another function to be decorated")
my_func2()
Page 68 of 93 wellsr.com
Python unittest Examples for Testing Python Code
More Info
def test_square(self):
num = 5
result = arithmetic.take_square(num)
self.assertEqual(result, 25)
def test_cube(self):
num = 3
result = arithmetic.take_cube(num)
self.assertEqual(result, 27)
def test_power(self):
num1 = 2
num2 = 6
if __name__ == '__main__':
unittest.main()
Page 69 of 93 wellsr.com
Multithreading in Python: Running Functions in Parallel
More Info
class App1(Thread):
def my_function(self, name):
for i in range(5):
print("thread "+ str(name))
sleep(1)
app1 = App1()
t1 = Thread(target=app1.my_function, args=("alpha",))
t1.start()
t2 = Thread(target=app1.my_function, args=("beta",))
t2.start()
Page 70 of 93 wellsr.com
3 Ways to Calculate Python Execution Time
More Info
Page 71 of 93 wellsr.com
Understanding Python if __name__ == '__main__'
statements
More Info
Page 72 of 93 wellsr.com
How to Read PDF Files with Python using PyPDF2
More Info
URL = 'http://www.africau.edu/images/default/sample.pdf'
req = urllib.request.Request(URL, headers={'User-Agent' : "Magic Browser"})
remote_file = urllib.request.urlopen(req).read()
remote_file_bytes = io.BytesIO(remote_file)
pdfdoc_remote = PyPDF2.PdfFileReader(remote_file_bytes)
for i in range(pdfdoc.numPages):
current_page = pdfdoc.getPage(i)
print("===================")
print("Content on page:" + str(i + 1))
print("===================")
print(current_page.extractText())
Page 73 of 93 wellsr.com
How to use the Python pdb debugger
More Info
import pdb
Page 74 of 93 wellsr.com
Python Face Detection for Beginners with OpenCV
More Info
result = get_detected_face(face1)
plt.imshow(result, cmap = "gray")
plt.show()
Page 75 of 93 wellsr.com
Convert Image to String with Python Pytesseract OCR
More Info
Ticket: 01
Item $0,00
Total $0.00
Page 76 of 93 wellsr.com
Python Image Manipulation with Pillow Library
More Info
all_images = os.listdir(source_path)
Page 77 of 93 wellsr.com
Drawing Shapes on Images with the Python OpenCV Library
More Info
cv2.rectangle(
image_correct,
pt1 = (300,100), pt2 = (600,300),
color = (255,0,255),
thickness = 10
)
plt.imshow(image_correct)
Page 78 of 93 wellsr.com
Python chdir and getcwd to Set Working Directory
More Info
Page 79 of 93 wellsr.com
List Files in a Folder With Python OS listdir and walk
More Info
Page 80 of 93 wellsr.com
How to Open Files with Python OS
More Info
Page 81 of 93 wellsr.com
Python OS Delete Files and Create Folders
More Info
Page 82 of 93 wellsr.com
Logging Info and Errors with the Python Logging Module
More Info
i = 0
def list_divide(nums1, nums2):
global i
i = i + 1
my_logger.info("Function called " + str(i) + " times")
my_logger.info("Numerator list" + str(nums1))
my_logger.info("Denominator list" + str(nums2))
try:
result = []
for num,den in zip(nums1, nums2):
result.append(num/den)
return result
except Exception as e:
print("an error occured")
my_logger.error(e)
Page 83 of 93 wellsr.com
Random Number Generation in Python with Random Module
More Info
Page 84 of 93 wellsr.com
Python Delete All Files in a Folder
More Info
Page 85 of 93 wellsr.com
Python Map, Filter and Reduce for Lambda Functions
More Info
Page 86 of 93 wellsr.com
Sorting items in Python using Sort and Sorted Methods
More Info
print(students)
print(students_sorted)
Page 87 of 93 wellsr.com
NumPy Eigenvalues and Eigenvectors with Python
More Info
Page 88 of 93 wellsr.com
Outer Product of Two Vectors or Matrices with Python
NumPy
More Info
m1 = np.array([[4,1,8],
[3,5,7],
[7,2,6]])
m2 = np.array([[7,2,9],
[3,1,2],
[4,2,9]])
print("Original Vectors:")
print(m1)
print(m2)
print("Outer product:")
op = np.outer(m1, m2)
print(op)
Page 89 of 93 wellsr.com
Python k-means clustering with scikit-learn
More Info
import numpy as np
import pandas as pd
#load dataset
X = pd.read_csv('https://raw.githubusercontent.com/krishnaik06/DBSCAN-Algorithm/master/Mall_Customers.csv')
X.head()
Page 90 of 93 wellsr.com
Asynchronous Programming in Python with Asyncio
More Info
print("Item 1")
#add sleep to add a dummy wait
await asyncio.sleep(2)
print("item 2")
print("Price 1")
print("Price 2")
asyncio.run(parent_func())
Page 91 of 93 wellsr.com
Python Agglomerative Clustering with sklearn
More Info
Page 92 of 93 wellsr.com
Python PCA Examples with sklearn
More Info
pca_model = PCA(n_components=2)
X_train_pca = pca_model.fit_transform(X_train)
X_test_pca = pca_model.transform(X_test)
print(accuracy_score(y_test, y_pred)
Page 93 of 93 wellsr.com