Refactor this code import requests import pandas as pd import sqlite3 from bs4 import…
- User
Refactor this code
import requests import pandas as pd import sqlite3 from bs4 import BeautifulSoup from datetime import datetime
Task 1: Log Progress
I'm kind of confused as to what "Use the list of log points provided" means,
so I just guessed where to place the log statements
def log_progress(message): with open('code_log.txt', 'a') as log_file: now = datetime.now().strftime('%Y-%m-%d %H:%M:%S:') log_file.write(f"{now}: {message}\n") log_file.close()
Task 2: Extract Data
def extract(): log_progress("Extracting data...") url = "https://web.archive.org/web/20230908091635/https://en.wikipedia.org/wiki/List_of_largest_banks" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')
# Get the first html table from the article on the page table = soup.find('table', {'class': 'wikitable'}) rows = table.find_all('tr') data = [] # The task says that I need to extract the first 10 banks, but there are # 10 banks in total lol for row in rows[1:11]: cols = row.find_all('td') rank = cols[0].get_text(strip=True) name = cols[1].get_text(strip=True) mc_usd = float(cols[2].get_text(strip=True).replace(',', '')) data.append([name, mc_usd]) df = pd.DataFrame(data, columns=['Name', 'MC_USD_Billion']) log_progress("Data extracted successfully") return dfTask 3: Transform Data
def transform(df): log_progress("Transforming data...") # The task said to download the csv, but what's the point # when I can read it directly from the url? Also, I feel like it makes # way more sense to get exchange rates from a remote source, compared to # a local file exchange_rate_df = pd.read_csv("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMSkillsNetwork-PY0221EN-Coursera/labs/v2/exchange_rate.csv")
rates = dict(zip(exchange_rate_df.Currency, exchange_rate_df.Rate)) df['MC_GBP_Billion'] = (df['MC_USD_Billion'] * rates['GBP']).round(2) df['MC_EUR_Billion'] = (df['MC_USD_Billion'] * rates['EUR']).round(2) df['MC_INR_Billion'] = (df['MC_USD_Billion'] * rates['INR']).round(2) log_progress("Data transformed successfully") return dfTask 4: Load to CSV
def load_to_csv(df): log_progress("Loading data to CSV...") df.to_csv('./Largest_banks_data.csv', index=False) log_progress("Data loaded to CSV successfully")
Task 5: Load to Database
The task make it seem like I load the data into the database AND
also run queries against the newly created table, but I feel like
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.