Emoji Print
Installed pip
emoji module for easy emoji insertion. very fun to insert random emojis in text
# terminal command to install library
$ pip install emoji
Collecting emoji
Downloading emoji-2.5.1.tar.gz (356 kB)
...
Successfully installed emoji-2.5.1
#!pip install emoji
from emoji import emojize
print(emojize(":thumbs_up: Python is awesome! :grinning_face:"))
👍 Python is awesome! 😀
Extracting Data
Code using a library called newspaper, extracts a couple of writeups from the CNN Entertainment site. newspaper3k wikipedia
#!pip install newspaper3k
from newspaper import Article
from IPython.display import display, Markdown
urls = ["http://cnn.com/2023/03/29/entertainment/the-mandalorian-episode-5-recap/index.html",
"https://www.cnn.com/2023/06/09/entertainment/jurassic-park-anniversary/index.html"]
for url in urls:
article = Article(url)
article.download()
article.parse()
# Jupyter Notebook Display
# print(article.title)
display(Markdown(article.title)) # Jupyter display only
display(Markdown(article.text)) # Jupyter display only
print("\n")
Experimental code for wikipedia module
The following sequence of code takes input from the user and searches for that keyword on wikipedia, providing info as a summary to the user. uses a whie loop to run until user inputs ‘no’ and for loop to then find all desired articles.
#!pip install wikipedia
import wikipedia
from IPython.display import display, Markdown # add for Jupyter
ks = []
print("Enter inputs to search for. To quit, enter 'no'.")
thing = 'yes' # initialize thing
while thing.lower() != 'no':
thing = input()
if thing == 'no': # don't search for 'no'
break
ks.append(thing)
for keyword in ks:
# Search for a page with user-given keyword
result = wikipedia.search(keyword)
# Get the summary of the first result
summary = wikipedia.summary(result[0])
print(keyword)
# print(summary) # console display
display(Markdown(summary)) # Jupyter display
'''vvv USER OUTPUT vvv'''
Enter inputs to search for. To quit, enter 'no'.
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2023, 98.7% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. All major web browsers have a dedicated JavaScript engine to execute the code on users’ devices. JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard. It has dynamic typing, prototype-based object-orientation, and first-class functions. It is multi-paradigm, supporting event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM). The ECMAScript standard does not include any input/output (I/O), such as networking, storage, or graphics facilities. In practice, the web browser or other runtime system provides JavaScript APIs for I/O. JavaScript engines were originally used only in web browsers, but are now core components of some servers and a variety of applications. The most popular runtime system for this usage is Node.js. Although Java and JavaScript are similar in name, syntax, and respective standard libraries, the two languages are distinct and differ greatly in design.
Inspecting a Function
The inspect module can give you the output of what’s inside many Python functions/objects. This can help you explore code behind what you are using.
- Inspect documentation.
import inspect
from newspaper import Article
# inspect newspaper Article function
print(inspect.getsource(Article))
Python Data Types
Dynamic typing means that the type of the variable is determined only during runtime. Strong typing means that variables do have a type and that the type matters when performing operations. In the illustration below there are two functions
- mean… shows types required prior to calling average function
- average, average2… calculates the average of a list of numbers
Python has types. In the language you can use type hints, but most coders do not use them. In other languages like Java and ‘C’ you must specify types.
import sys
from typing import Union
# Define types for mean function, trying to analyze input possibilities
Number = Union[int, float] # Number can be either int or float type
Numbers = list[Number] # Numbers is a list of Number types
Scores = Union[Number, Numbers] # Scores can be single or multiple
def mean(scores: Scores, method: int = 1) -> float: # method defaults to int, 1 if not given
"""
Calculate the mean of a list of scores.
Average and Average2 are hidden functions performing mean algorithm
If a single score is provided in scores, it is returned as the mean.
If a list of scores is provided, the average is calculated and returned.
"""
def average(scores):
"""Calculate the average of a list of scores using a Python for loop with rounding."""
sum = 0
len = 0
for score in scores:
if isinstance(score, Number): # score is int or float (used Union for this)
sum += score
len += 1
else:
print("Bad data: " + str(score) + " in " + str(scores))
raise SystemExit()
return sum / len
def average2(scores):
"""Calculate the average of a list of scores using the built-in sum() function with rounding."""
return sum(scores) / len(scores)
# test to see if scores is a list of numbers
if isinstance(scores, list):
if method == 1:
# long method
result = average(scores)
else:
# built in method
result = average2(scores)
return round(result + 0.005, 2) # round to 2 decimals
return scores # case where scores is a single value
# try with one number
singleScore = 100
print("The given test data: " + str(singleScore)) # concat data for single line
print("Mean of single number: " + str(mean(singleScore)))
print()
# define a list of numbers
testScores = [90.5, 100, 85.4, 88]
print("The given test data: " + str(testScores))
print("Average score, loop method: " + str(mean(testScores)))
print("Average score, function method: " + str(mean(testScores, 2)))
print()
badData = [100, "NaN", 90]
print("The given test data: " + str(badData))
print("Mean with bad data: " + str(mean(badData)))
The given test data: 100
Mean of single number: 100
The given test data: [90.5, 100, 85.4, 88]
Average score, loop method: 90.98
Average score, function method: 90.98
The given test data: [100, 'NaN', 90]
Bad data: NaN in [100, 'NaN', 90]
An exception has occurred, use %tb to see the full traceback.
SystemExit