Last active
September 28, 2023 14:41
-
-
Save tbennett6421/bf206c0e4c5555550bb82312d3fd529d to your computer and use it in GitHub Desktop.
python snippets.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################################ | |
### Standard | |
################################################################################ | |
### | |
### Comprehensions | |
### | |
# List Comprehension | |
resulting_list = [i for i in original_list_or_array] | |
resulting_list = [i**2 for i in original_list_or_array] | |
# Dict Comprehension | |
myDict = { k:v for (k,v) in zip(keys, values)} | |
### | |
### Dicts | |
### | |
# reverse a lookup index | |
rd = { v:k for (k,v) in d.items() } | |
# extract subset of dict | |
list(word_index.items())[:5] | |
### | |
### Looping | |
### | |
for idx, item in enumerate(my_tuple): | |
print(f'Item index: {idx}\tItem value: {item} | |
### | |
### Printing | |
### | |
# python 2+ | |
print("Item class: %s \t Value: %s" % ( type(item), item )) | |
# python 3.6+ | |
print(f'Item class: {type(item)}\tValue: {item}') | |
### Looping two elements at a time | |
input_string = "Hello, World!" | |
step = 2 | |
for i in range(0, len(input_string), step): | |
two_chars = input_string[i:i+step] | |
print(two_chars) | |
################################################################################ | |
### Libs | |
################################################################################ | |
### | |
### datetime | |
### | |
################################################################################ | |
# Getting the day of the week from a date | |
from datetime import date | |
date_input = input("Enter the date (mm/dd/yyyy): ") | |
date_list = date_input.split("/") | |
month = int(date_list[0]) | |
day = int(date_list[1]) | |
year = int(date_list[2]) | |
date_date = date(year, month, day) | |
n_day_of_week = date_date.weekday() | |
days_of_week = ( | |
"Monday", | |
"Tuesday", | |
"Wednesday", | |
"Thursday", | |
"Friday", | |
"Saturday", | |
"Sunday", | |
) | |
day_of_week = days_of_week[n_day_of_week] | |
print(day_of_week) | |
################################################################################ | |
### | |
### PIL | |
### | |
################################################################################ | |
# Getting the resolution of an image | |
from PIL import Image | |
image = input("Enter the image file name: ") | |
im = Image.open(image) | |
print('Image resolution is (w, h): ' + str(im.size)) | |
################################################################################ | |
################################################################################ | |
# Rotating images | |
from PIL import Image | |
image = input("Enter the image file name: ") | |
angle = input("Enter the rotation angle in degrees: ") | |
angle = float(angle) | |
im = Image.open(image) | |
im_rotate = im.rotate(angle, expand=True) | |
im_rotate.save("rotated_" + image) | |
################################################################################ | |
################################################################################ | |
# Resizing images | |
from PIL import Image | |
image = input("Enter the image file name: ") | |
width = input("Enter the new width: ") | |
height = input("Enter the new height: ") | |
im = Image.open(image) | |
width = int(width) | |
height = int(height) | |
im_resize = im.resize((width, height), resample=Image.BICUBIC) | |
im_resize.save("resized_" + image) | |
################################################################################ | |
### | |
### random | |
### | |
################################################################################ | |
# Generating a random password | |
import random | |
import string | |
use_digits_answer = input("Use digits [y]/n: ") | |
if use_digits_answer.lower() == "n": | |
use_digits = False | |
else: | |
use_digits = True | |
use_punctuation_answer = input("Use special characters [y]/n: ") | |
if use_punctuation_answer.lower() == "n": | |
use_punctuation = False | |
else: | |
use_punctuation = True | |
password_length_answer = input("Length of the password [10]: ") | |
if password_length_answer == "": | |
password_length = 10 | |
else: | |
password_length = int(password_length_answer) | |
letters = string.ascii_letters | |
digits = string.digits | |
punctuation = string.punctuation | |
symbols = letters | |
if use_digits: | |
symbols += digits | |
if use_punctuation: | |
symbols += punctuation | |
password = "".join(random.choice(symbols) for i in range(password_length)) | |
print(password) | |
################################################################################ | |
### | |
### requests / bs4 | |
### | |
################################################################################ | |
# Getting the list of links from a website | |
import requests | |
import re | |
url = input("Enter the URL: ") | |
html = requests.get(url).text | |
links = re.findall('"(https?://.*?)"', html) | |
for link in links: | |
print(link) | |
################################################################################ | |
################################################################################ | |
# parsing and getting elements with bs4 | |
import requests | |
from bs4 import BeautifulSoup | |
URL = "https://google.com/" | |
page = requests.get(URL) | |
# Find Elements by ID | |
soup = BeautifulSoup(page.content, "html.parser") | |
results = soup.find(id="ResultsContainer") | |
print(results.prettify()) | |
# Find Elements by HTML Class Name | |
job_elements = results.find_all("div", class_="card-content") | |
for job_element in job_elements: | |
print(job_element, end="\n"*2) | |
# Extract Text From HTML Elements | |
for job_element in job_elements: | |
title_element = job_element.find("h2", class_="title") | |
company_element = job_element.find("h3", class_="company") | |
location_element = job_element.find("p", class_="location") | |
print(title_element.text.strip()) | |
print(company_element.text.strip()) | |
print(location_element.text.strip()) | |
print() | |
#Find Elements by Class Name and Text Content | |
python_jobs = results.find_all( | |
"h2", string=lambda text: "python" in text.lower() | |
) | |
for job_element in python_jobs: | |
title_element = job_element.find("h2", class_="title") | |
company_element = job_element.find("h3", class_="company") | |
location_element = job_element.find("p", class_="location") | |
print(title_element.text.strip()) | |
print(company_element.text.strip()) | |
print(location_element.text.strip()) | |
print() | |
# Access Parent Elements | |
python_jobs = results.find_all( | |
"h2", string=lambda text: "python" in text.lower() | |
) | |
python_job_elements = [ | |
h2_element.parent.parent.parent for h2_element in python_jobs | |
] | |
for job_element in python_job_elements: | |
pass | |
# Extract Attributes From HTML Elements | |
for job_element in python_job_elements: | |
links = job_element.find_all("a") | |
for link in links: | |
link_url = link["href"] | |
print(f"Apply here: {link_url}\n") | |
for job_element in python_job_elements: | |
link_url = job_element.find_all("a")[1]["href"] | |
print(f"Apply here: {link_url}\n") | |
################################################################################ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment