Python Data Visualization with Gemini
Python Data Visualization with Gemini
Aim : Create a program that reads data from one file and writes it to another file in a
different format.
Code :
Output :
Experiment - 8
Aim : Create a program that uses regular expressions to find all instances of a specific
pattern in a text.
Code :
import re
text = "My email is example@[Link] and my friend's email is
test123@[Link]."
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{2,}'
emails = [Link](pattern, text)
print("Extracted Emails:", emails)
Output :
Experiment - 9
Aim : Create a program that prompts the user for two numbers and divides them, handling
any exceptions.
Code :
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter numbers only.")
Output :
Experiment - 10
Aim : Create a program that uses a graphical user interface (GUI) to allow the user to
perform simple calculations.
Code :
import tkinter as tk
def calculate():
try:
num1 = float([Link]())
num2 = float([Link]())
[Link](f"Result: {num1 + num2}")
except ValueError:
[Link]("Invalid input")
root = [Link]()
[Link]("Simple Calculator")
[Link]("300x200")
[Link](False, False)
FONT = ("Helvetica", 12)
PAD = {'padx': 10, 'pady': 10}
[Link](root, text="Enter first number:", font=FONT).grid(row=0, column=0,
sticky="w", **PAD)
entry1 = [Link](root, font=FONT)
[Link](row=0, column=1, **PAD)
[Link](root, text="Enter second number:", font=FONT).grid(row=1,
column=0, sticky="w", **PAD)
entry2 = [Link](root, font=FONT)
[Link](row=1, column=1, **PAD)
result = [Link]()
[Link](root, textvariable=result, font=FONT, fg="blue").grid(row=2,
column=0, columnspan=2, **PAD)
[Link](root, text="Add", command=calculate, font=FONT, bg="#4CAF50",
fg="white").grid(row=3, column=0, columnspan=2, **PAD)
[Link]()
Output :
Experiment - 11
Aim : Create a Python program that uses a web scraping library to extract data
(hyperlinks) from a website and then stores it in a SQLite database.
Code :
import requests
from bs4 import BeautifulSoup
import sqlite3
def scrape_data(url):
response = [Link](url)
if response.status_code != 200:
print(f"Failed to retrieve the page: {response.status_code}")
return []
soup = BeautifulSoup([Link], '[Link]')
data = []
for item in soup.find_all('a'):
text = item.get_text(strip=True)
if text:
[Link](text)
return data
def create_database():
conn = [Link]('scraped_data.db')
cursor = [Link]()
[Link]('''
CREATE TABLE IF NOT EXISTS scraped_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT
)''')
[Link]()
return conn, cursor
def main():
url = '[Link]
data = scrape_data(url)
if data:
print(f"Scraped {len(data)} items")
print("Scraped Data: ", data)
conn, cursor = create_database()
insert_data(cursor, data)
print("Data stored in the database successfully.")
[Link]()
else:
print("No data to store.")
if __name__ == "__main__":
main()
Output :
Experiment - 12
Aim : Create a program that reads data from a file and then creates a visualization of that
data using a data visualization library.
Code :
import pandas as pd
import [Link] as plt
def read_data(file_path):
df = pd.read_csv(file_path)
return df
def create_visualization(df):
[Link](figsize=(8, 6))
[Link](df['Category'], df['Value'], color='skyblue')
[Link]('Category vs Value')
[Link]('Category')
[Link]('Value')
[Link]()
def main():
file_path = '[Link]'
df = read_data(file_path)
if [Link]:
print("Error: No data found in the file.")
return
create_visualization(df)
if __name__ == "__main__":
main()
Output :
Experiment - 13
Aim : Create a program that uses a machine learning library to classify images based on
their content using a pre-trained model.
Code :
import torch
import [Link] as nn
from torchvision import models, transforms
from PIL import Image
import requests
from io import BytesIO
import json
img_tensor = transform(img)
img_tensor = img_tensor.unsqueeze(0) # Add batch dimension
return img_tensor
with torch.no_grad():
outputs = model(img_tensor)
_, predicted_idx = [Link](outputs, 1)
Output :
Experiment - 14
Aim : Create a program that uses a networking library to communicate with a server and
retrieve data from it.
Code :
import requests
def get_data_from_server(url):
try:
response = [Link](url)
if response.status_code == 200:
print("✅ Data received successfully:")
print([Link]) # Raw HTML or JSON/text response
else:
print(f"❌ Failed to retrieve data. HTTP Status code:
{response.status_code}")
except [Link] as e:
# Handle network or connection errors
print(f"⚠ An error occurred: {e}")
def main():
url = input("Enter the server URL to retrieve data from (e.g.,
[Link] ")
get_data_from_server(url)
if __name__ == "__main__":
main()
Output :