diff --git a/Aaluru_Bhavana/Task9-imgconv/TASK-9.py b/Aaluru_Bhavana/Task9-imgconv/TASK-9.py new file mode 100644 index 0000000..fcd4fc3 --- /dev/null +++ b/Aaluru_Bhavana/Task9-imgconv/TASK-9.py @@ -0,0 +1,37 @@ +from PIL import Image +import os + +def convert_image(input_path, output_path, output_format): + try: + # Open the image + with Image.open(input_path) as img: + # Check if the image has an alpha channel and convert it to RGB if necessary + if output_format == 'JPEG' and img.mode == 'RGBA': + img = img.convert('RGB') + + # Convert and save the image to the desired format + img.save(output_path, format=output_format) + print(f"Image converted successfully to {output_format} format.") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + input_path = input("Enter the path to the input image: ") + output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper() + + # Validate output format + if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']: + print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.") + return + + # Extract the file name and extension + file_name, file_extension = os.path.splitext(input_path) + + # Set the output path + output_path = f"{file_name}_converted.{output_format.lower()}" + + # Convert the image + convert_image(input_path, output_path, output_format) + +if __name__ == "__main__": + main() diff --git a/Aaluru_Bhavana/task1/TASK-1.py b/Aaluru_Bhavana/task1/TASK-1.py new file mode 100644 index 0000000..1422fc1 --- /dev/null +++ b/Aaluru_Bhavana/task1/TASK-1.py @@ -0,0 +1,30 @@ +#a simple python program to perform basic tasks like addition,subtraction,multiplication,division +print('please select any of the number for performing arithmetic operations') +print("1.Addition") +print('2.Subtraction') +print('3.Multiplication') +print('4.Division') +print('5.exit') +a=int(input('Enter any of the number for performing arithmetic operations')) +def ari(a,var1,var2): + a,var1,var2=a,var1,var2 + if(a==1): + print(var1+var2) + if(a==2): + print(var1-var2) + if(a==3): + print(var1*var2) + if(a==4): + print(var1/var2) + return + +#Enter Two numbers +if((a>0) and (a<5)): + var1 = int(input('Enter First number: ')) + var2 = int(input('Enter Second number: ')) + ari(a,var1,var2) +elif(a==5): + exit() +else: + print('Invalid Option') + print('please select 1/2/3/4/5 only') \ No newline at end of file diff --git a/Aaluru_Bhavana/task10/TASK-10.py b/Aaluru_Bhavana/task10/TASK-10.py new file mode 100644 index 0000000..2fee7c7 --- /dev/null +++ b/Aaluru_Bhavana/task10/TASK-10.py @@ -0,0 +1,43 @@ +import seaborn as sns +import pandas as pd +import matplotlib.pyplot as plt + +# Load the Iris dataset from Seaborn +iris = sns.load_dataset("iris") +numeric_iris = iris.drop(columns='species') + +# Display the first few rows of the dataset +print("First few rows of the dataset:") +print(iris.head()) + +# Summary statistics +print("\nSummary statistics:") +print(iris.describe()) + +# Checking for missing values +print("\nMissing values:") +print(iris.isnull().sum()) + +# Visualizations +# Pairplot +sns.pairplot(iris, hue="species") +plt.title("Pairplot of Iris Dataset") +plt.show() + +# Boxplot +plt.figure(figsize=(10, 6)) +sns.boxplot(data=iris, orient="h") +plt.title("Boxplot of Iris Dataset") +plt.show() + +# Histograms +plt.figure(figsize=(10, 6)) +iris.hist() +plt.suptitle("Histograms of Iris Dataset") +plt.show() + +# Correlation heatmap +plt.figure(figsize=(8, 6)) +sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm") +plt.title("Correlation Heatmap of Iris Dataset") +plt.show() diff --git a/Aaluru_Bhavana/task11/TASK-11.py b/Aaluru_Bhavana/task11/TASK-11.py new file mode 100644 index 0000000..85bc4e1 --- /dev/null +++ b/Aaluru_Bhavana/task11/TASK-11.py @@ -0,0 +1,40 @@ +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error + +# Fetch the Boston housing dataset from the original source +data_url = "http://lib.stat.cmu.edu/datasets/boston" +raw_df = pd.read_csv(data_url, sep=r"\s+", skiprows=22, header=None) +data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]]) +target = raw_df.values[1::2, 2] + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) + +# Create and train the linear regression model +model = LinearRegression() +model.fit(X_train, y_train) + +# Make predictions on the training and testing sets +y_train_pred = model.predict(X_train) +y_test_pred = model.predict(X_test) + +# Calculate the mean squared error for training and testing sets +train_mse = mean_squared_error(y_train, y_train_pred) +test_mse = mean_squared_error(y_test, y_test_pred) + +print("Train MSE:", train_mse) +print("Test MSE:", test_mse) + +# Plot residuals +plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data') +plt.scatter(y_test_pred, y_test_pred - y_test, c='green', marker='s', label='Test data') +plt.xlabel('Predicted values') +plt.ylabel('Residuals') +plt.legend(loc='upper left') +plt.hlines(y=0, xmin=min(y_train_pred.min(), y_test_pred.min()), xmax=max(y_train_pred.max(), y_test_pred.max()), color='red') +plt.title('Residuals plot') +plt.show() diff --git a/Aaluru_Bhavana/task12/TASK-12.py b/Aaluru_Bhavana/task12/TASK-12.py new file mode 100644 index 0000000..98c044f --- /dev/null +++ b/Aaluru_Bhavana/task12/TASK-12.py @@ -0,0 +1,66 @@ +from PIL import Image +import os + +def get_size_format(b, factor=1024, suffix="B"): + """ + Scale bytes to its proper byte format. + e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB' + """ + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if b < factor: + return f"{b:.2f}{unit}{suffix}" + b /= factor + return f"{b:.2f}Y{suffix}" + +def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): + try: + # Load the image into memory + img = Image.open(image_name) + + # Print the original image shape + print("[*] Image shape:", img.size) + + # Get the original image size in bytes + image_size = os.path.getsize(image_name) + print("[*] Size before compression:", get_size_format(image_size)) + + if width and height: + # If width and height are set, resize with them instead + img = img.resize((width, height), Image.LANCZOS) + elif new_size_ratio < 1.0: + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS) + + # Split the filename and extension + filename, ext = os.path.splitext(image_name) + + # Make a new filename appending "_compressed" to the original file name + if to_jpg: + # Change the extension to JPEG + new_filename = f"{filename}_compressed.jpg" + # Ensure image is in RGB mode for JPEG + if img.mode in ("RGBA", "LA"): + img = img.convert("RGB") + else: + # Retain the same extension of the original image + new_filename = f"{filename}_compressed{ext}" + + # Save the compressed image + img.save(new_filename, optimize=True, quality=quality) + + # Print the new image shape + print("[+] New Image shape:", img.size) + + # Get the new image size in bytes + new_image_size = os.path.getsize(new_filename) + print("[*] Size after compression:", get_size_format(new_image_size)) + print(f"[*] Compressed image saved as: {new_filename}") + + except FileNotFoundError: + print("Error: The file was not found.") + except OSError as e: + print(f"Error: {e}") + +# Example usage: +input_image = input("Enter the path to the image: ") +compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600) diff --git a/Aaluru_Bhavana/task2/TASK-2.py b/Aaluru_Bhavana/task2/TASK-2.py new file mode 100644 index 0000000..1eacb0a --- /dev/null +++ b/Aaluru_Bhavana/task2/TASK-2.py @@ -0,0 +1,59 @@ +class TaskManager: + def __init__(self): + self.tasks = [] + + def add_task(self, task): + self.tasks.append({"task": task, "completed": False}) + + def delete_task(self, index): + if 0 <= index < len(self.tasks): + del self.tasks[index] + else: + print("Invalid task index") + + def mark_task_completed(self, index): + if 0 <= index < len(self.tasks): + self.tasks[index]["completed"] = True + else: + print("Invalid task index") + + def display_tasks(self): + print("Tasks:") + for i, task in enumerate(self.tasks): + status = "Completed" if task["completed"] else "Pending" + print(f"{i+1}. {task['task']} - {status}") + + +def main(): + task_manager = TaskManager() + + while True: + print("\nOptions:") + print("1. Add Task") + print("2. Delete Task") + print("3. Mark Task as Completed") + print("4. View Tasks") + print("5. Exit") + + choice = input("Enter your choice: ") + + if choice == "1": + task = input("Enter the task: ") + task_manager.add_task(task) + elif choice == "2": + index = int(input("Enter the index of the task to delete: ")) - 1 + task_manager.delete_task(index) + elif choice == "3": + index = int(input("Enter the index of the task to mark as completed: ")) - 1 + task_manager.mark_task_completed(index) + elif choice == "4": + task_manager.display_tasks() + elif choice == "5": + print("Exiting...") + break + else: + print("Invalid choice. Please try again.") + + +if __name__ == "__main__": + main() diff --git a/Aaluru_Bhavana/task3/TASK-3.py b/Aaluru_Bhavana/task3/TASK-3.py new file mode 100644 index 0000000..f1bc4c2 --- /dev/null +++ b/Aaluru_Bhavana/task3/TASK-3.py @@ -0,0 +1,33 @@ +import random + +def guess_number(): + # Generate a random number between 1 and 100 + secret_number = random.randint(1, 100) + attempts = 0 + max_attempts = 10 + + print("Welcome to the Number Guessing Game!") + print("I have chosen a number between 1 and 100. You have", max_attempts, "attempts to guess it.") + + while attempts < max_attempts: + try: + guess = int(input("Enter your guess: ")) + except ValueError: + print("Invalid input! Please enter a valid number.") + continue + + attempts += 1 + + if guess < secret_number: + print("Too low! Try again.") + elif guess > secret_number: + print("Too high! Try again.") + else: + print("Congratulations! You've guessed the number", secret_number, "correctly in", attempts, "attempts!") + break + else: + print("Sorry, you've run out of attempts. The correct number was", secret_number) + +if __name__ == "__main__": + guess_number() + diff --git a/Aaluru_Bhavana/task4/TASK-4.py b/Aaluru_Bhavana/task4/TASK-4.py new file mode 100644 index 0000000..2b9f9ea --- /dev/null +++ b/Aaluru_Bhavana/task4/TASK-4.py @@ -0,0 +1,93 @@ +import PyPDF2 +from PIL import Image +import os + + +def convert_pdf_to_text(pdf_path, text_output_path): + """Converts a PDF file to text. + + Args: + pdf_path (str): Path to the input PDF file. + text_output_path (str): Path to save the converted text file. + """ + try: + with open(pdf_path, 'rb') as pdf_file: + pdf_reader = PyPDF2.PdfReader(pdf_file) + with open(text_output_path, 'w', encoding='utf-8') as text_file: + # Iterate through each page of the PDF + for page_num in range(len(pdf_reader.pages)): + page = pdf_reader.pages[page_num] + # Extract text from the page and write it to the text file + text_file.write(page.extract_text()) + print(f"PDF converted to text successfully. Text file saved at {text_output_path}") + except Exception as e: + print(f"An error occurred: {e}") + + +def extract_images_from_pdf(pdf_path, image_output_folder): + """Extracts images from a PDF file. + + Args: + pdf_path (str): Path to the input PDF file. + image_output_folder (str): Folder to save the extracted images. + """ + try: + with open(pdf_path, 'rb') as pdf_file: + pdf_reader = PyPDF2.PdfReader(pdf_file) + # Iterate through each page of the PDF + for page_num in range(len(pdf_reader.pages)): + page = pdf_reader.pages[page_num] + xObject = page['/Resources']['/XObject'].getObject() + for obj in xObject: + if xObject[obj]['/Subtype'] == '/Image': + size = (xObject[obj]['/Width'], xObject[obj]['/Height']) + data = xObject[obj]._data + mode = '' + if xObject[obj]['/ColorSpace'] == '/DeviceRGB': + mode = "RGB" + else: + mode = "P" + if xObject[obj]['/Filter'] == '/FlateDecode': + img = Image.frombytes(mode, size, data) + img.save(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.png")) + elif xObject[obj]['/Filter'] == '/DCTDecode': + img = open(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.jpg"), "wb") + img.write(data) + img.close() + elif xObject[obj]['/Filter'] == '/JPXDecode': + img = open(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.jp2"), "wb") + img.write(data) + img.close() + print(f"Images extracted successfully. Saved in {image_output_folder}") + except Exception as e: + print(f"An error occurred: {e}") + + +def main(): + # Get input paths and output folder from user + pdf_path = input("Enter the path to the PDF file: ") + output_folder = input("Enter the output folder path: ") + + # Create the output folder if it does not exist + if not os.path.exists(output_folder): + os.makedirs(output_folder) + + # Choose conversion option + choice = input("Choose an option:\n1. Convert PDF to text\n2. Extract images from PDF\nEnter your choice: ") + + if choice == '1': + # Convert PDF to text + text_output_path = os.path.join(output_folder, "converted_text.txt") + convert_pdf_to_text(pdf_path, text_output_path) + elif choice == '2': + # Extract images from PDF + image_output_folder = os.path.join(output_folder, "extracted_images") + if not os.path.exists(image_output_folder): + os.makedirs(image_output_folder) + extract_images_from_pdf(pdf_path, image_output_folder) + else: + print("Invalid choice. Please choose 1 or 2.") + + +if __name__ == "__main__": + main() diff --git a/Aaluru_Bhavana/task5/TASK-5.py b/Aaluru_Bhavana/task5/TASK-5.py new file mode 100644 index 0000000..a9c61c2 --- /dev/null +++ b/Aaluru_Bhavana/task5/TASK-5.py @@ -0,0 +1,65 @@ +import requests +import datetime + +# Your OpenWeatherMap API key +API_KEY = '69e7dd8a8069d4066de2a18ea5996e36' +BASE_URL = 'http://api.openweathermap.org/data/2.5/' + +# Function to get current weather data +def get_current_weather(city): + url = f"{BASE_URL}weather?q={city}&appid={API_KEY}&units=metric" + response = requests.get(url) + return response.json() + +# Function to get weather forecast data +def get_forecast(city): + url = f"{BASE_URL}forecast?q={city}&appid={API_KEY}&units=metric" + response = requests.get(url) + return response.json() + +# Function to display weather data +def display_weather_data(city): + current_weather = get_current_weather(city) + forecast = get_forecast(city) + + if current_weather.get("cod") != 200 or forecast.get("cod") != "200": + print("Failed to retrieve data. Please check the city name or API key.") + return + + # Current weather + print(f"\nCurrent weather in {city.capitalize()}:") + print(f"Temperature: {current_weather['main']['temp']}°C") + print(f"Weather: {current_weather['weather'][0]['description']}") + print(f"Humidity: {current_weather['main']['humidity']}%") + print(f"Wind Speed: {current_weather['wind']['speed']} m/s") + + # Forecast + print(f"\n5-Day Forecast for {city.capitalize()}:") + for item in forecast['list']: + timestamp = item['dt'] + date_time = datetime.datetime.fromtimestamp(timestamp) + if date_time.hour == 12: # Show data for 12 PM each day + temp = item['main']['temp'] + weather = item['weather'][0]['description'] + print(f"{date_time.strftime('%Y-%m-%d %H:%M:%S')}: {temp}°C, {weather}") + + # Temperature trends (Average temperatures per day) + temp_trends = {} + for item in forecast['list']: + date = datetime.datetime.fromtimestamp(item['dt']).date() + if date not in temp_trends: + temp_trends[date] = [] + temp_trends[date].append(item['main']['temp']) + + print(f"\nTemperature Trends in {city.capitalize()}:") + for date, temps in temp_trends.items(): + avg_temp = sum(temps) / len(temps) + print(f"{date}: {avg_temp:.2f}°C") + +# Main function +def main(): + city = input("Enter the city name: ") + display_weather_data(city) + +if __name__ == "__main__": + main() diff --git a/Aaluru_Bhavana/task6/TASK-6.py b/Aaluru_Bhavana/task6/TASK-6.py new file mode 100644 index 0000000..b0d5169 --- /dev/null +++ b/Aaluru_Bhavana/task6/TASK-6.py @@ -0,0 +1,97 @@ +import requests +from bs4 import BeautifulSoup +import pandas as pd +import json +from urllib.parse import urljoin + +# Function to check robots.txt for scraping permission +def check_robots_txt(base_url): + robots_url = urljoin(base_url, '/robots.txt') + response = requests.get(robots_url) + if response.status_code == 200: + robots_txt = response.text + if "Disallow: /" in robots_txt: + return False + return True + return False + +# Function to list all tables in the HTML +def list_tables(soup): + tables = soup.find_all("table") + if not tables: + raise Exception("No tables found on the webpage.") + table_summaries = [] + for i, table in enumerate(tables): + summary = table.attrs.get("summary", f"Table {i+1}") + table_summaries.append(summary) + return tables, table_summaries + +# Function to extract data from the selected table +def extract_data(table): + data = [] + headers = [header.text.strip() for header in table.find_all("th")] + rows = table.find_all("tr")[1:] # Skipping the header row + for row in rows: + cells = row.find_all("td") + row_data = [cell.text.strip() for cell in cells] + data.append(row_data) + return headers, data + +# Main function to perform web scraping +def main(): + # Read the URL from the user + base_url = input("Enter the URL of the website to scrape: ") + + # Check if scraping is allowed + if not check_robots_txt(base_url): + print("It is not possible to perform web scraping on this website.") + return + + # Send a GET request to fetch the raw HTML content + response = requests.get(base_url) + if response.status_code != 200: + raise Exception(f"Failed to load page {base_url}") + + # Parse the content with BeautifulSoup + soup = BeautifulSoup(response.content, "html.parser") + + # List all tables + try: + tables, table_summaries = list_tables(soup) + except Exception as e: + print(f"Error during table listing: {e}") + return + + # Display the tables to the user and ask for a selection + print("Tables found on the webpage:") + for i, summary in enumerate(table_summaries): + print(f"{i + 1}: {summary}") + + try: + table_index = int(input("Enter the number of the table you want to scrape: ")) - 1 + if table_index < 0 or table_index >= len(tables): + raise ValueError("Invalid table number selected.") + except ValueError as e: + print(f"Error during table selection: {e}") + return + + # Extract data from the selected table + try: + headers, data = extract_data(tables[table_index]) + except Exception as e: + print(f"Error during data extraction: {e}") + return + + # Convert to DataFrame + df = pd.DataFrame(data, columns=headers) + + # Save to CSV + df.to_csv("scraped_data.csv", index=False) + + # Save to JSON + df.to_json("scraped_data.json", orient="records") + + print("Data has been scraped and saved to scraped_data.csv and scraped_data.json") + +if __name__ == "__main__": + main() diff --git a/Aaluru_Bhavana/task7/TASK-7.py b/Aaluru_Bhavana/task7/TASK-7.py new file mode 100644 index 0000000..66157af --- /dev/null +++ b/Aaluru_Bhavana/task7/TASK-7.py @@ -0,0 +1,26 @@ +import nltk +from nltk.chat.util import Chat, reflections + +# Define pairs of patterns and responses +pairs = [ + (r'hi|hello|hey', ['Hello!', 'Hey there!', 'Hi! How can I help you?']), + (r'how are you?', ['I\'m doing well, thank you!', 'I\'m good, thanks for asking!']), + (r'what\'s your name\??', ['I\'m a chatbot!', 'You can call me ChatBot.']), + (r'(.*) your name\??', ['I\'m a chatbot!', 'You can call me ChatBot.']), + # Add more patterns and responses as needed +] + +# Create a Chatbot instance +chatbot = Chat(pairs, reflections) + +print("Welcome! Type 'quit' to end the conversation.") + +# Start the conversation loop +while True: + user_input = input("You: ") + if user_input.lower() == 'quit': + print("ChatBot: Bye! Have a great day!") + break + else: + response = chatbot.respond(user_input) + print("ChatBot:", response) diff --git a/Aaluru_Bhavana/task8/TASK-8.py b/Aaluru_Bhavana/task8/TASK-8.py new file mode 100644 index 0000000..61b10ce --- /dev/null +++ b/Aaluru_Bhavana/task8/TASK-8.py @@ -0,0 +1,61 @@ + +import os +from PyPDF2 import PdfMerger, PdfReader, PdfWriter + +def merge_pdfs(pdf_list, output_path): + merger = PdfMerger() + + for pdf in pdf_list: + if os.path.exists(pdf): + merger.append(pdf) + else: + print(f"File not found: {pdf}") + + with open(output_path, 'wb') as output_file: + merger.write(output_file) + + print(f'Merged PDF saved as {output_path}') + +def split_pdf(input_path, output_folder): + if not os.path.exists(input_path): + print(f"File not found: {input_path}") + return + + with open(input_path, 'rb') as input_file: + reader = PdfReader(input_file) + num_pages = len(reader.pages) + + for page_num in range(num_pages): + writer = PdfWriter() + writer.add_page(reader.pages[page_num]) + + output_path = os.path.join(output_folder, f'page_{page_num + 1}.pdf') + with open(output_path, 'wb') as output_file: + writer.write(output_file) + + print(f'Saved {output_path}') + +def main(): + print("PDF Merger/Splitter") + print("1. Merge PDFs") + print("2. Split PDF") + print("3. Exit") + choice = input("Enter your choice: ") + + if choice == '1': + pdf_files = input("Enter the PDF files to merge (separated by commas): ").split(',') + pdf_files = [pdf.strip() for pdf in pdf_files] # Strip whitespace + output_path = input("Enter the output path for the merged PDF: ") + merge_pdfs(pdf_files, output_path) + elif choice == '2': + input_path = input("Enter the PDF file to split: ") + output_folder = input("Enter the output folder for the split PDFs: ") + os.makedirs(output_folder, exist_ok=True) + split_pdf(input_path, output_folder) + elif choice == '3': + print("Exiting.") + else: + print("Invalid choice. Exiting.") + +if __name__ == "__main__": + main() diff --git a/Calc.py b/Calc.py new file mode 100644 index 0000000..952e22b --- /dev/null +++ b/Calc.py @@ -0,0 +1,30 @@ +#a simple python program to perform basic tasks like addition,subtraction,multiplication,division +print('please select any of the number for performing arithmetic operations') +print("1.Addition") +print('2.Subtraction') +print('3.Multiplication') +print('4.Division') +print('5.exit') +a=int(input('Enter any of the number for performing arithmetic operations')) +def ari(a,var1,var2): + a,var1,var2=a,var1,var2 + if(a==1): + print(var1+var2) + if(a==2): + print(var1-var2) + if(a==3): + print(var1*var2) + if(a==4): + print(var1/var2) + return + +#Enter Two numbers +if((a>0) and (a<5)): + var1 = int(input('Enter First number: ')) + var2 = int(input('Enter Second number: ')) + ari(a,var1,var2) +elif(a==5): + exit() +else: + print('Invalid Option') + print('please select 1/2/3/4/5 only') \ No newline at end of file diff --git a/TASK-10.py b/TASK-10.py new file mode 100644 index 0000000..365c14e --- /dev/null +++ b/TASK-10.py @@ -0,0 +1,43 @@ +import seaborn as sns +import pandas as pd +import matplotlib.pyplot as plt + +# Load the Iris dataset from Seaborn +iris = sns.load_dataset("iris") +numeric_iris = iris.drop(columns='species') + +# Display the first few rows of the dataset +print("First few rows of the dataset:") +print(iris.head()) + +# Summary statistics +print("\nSummary statistics:") +print(iris.describe()) + +# Checking for missing values +print("\nMissing values:") +print(iris.isnull().sum()) + +# Visualizations +# Pairplot +sns.pairplot(iris, hue="species") +plt.title("Pairplot of Iris Dataset") +plt.show() + +# Boxplot +plt.figure(figsize=(10, 6)) +sns.boxplot(data=iris, orient="h") +plt.title("Boxplot of Iris Dataset") +plt.show() + +# Histograms +plt.figure(figsize=(10, 6)) +iris.hist() +plt.suptitle("Histograms of Iris Dataset") +plt.show() + +# Correlation heatmap +plt.figure(figsize=(8, 6)) +sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm") +plt.title("Correlation Heatmap of Iris Dataset") +plt.show() diff --git a/TASK-11.py b/TASK-11.py new file mode 100644 index 0000000..195849c --- /dev/null +++ b/TASK-11.py @@ -0,0 +1,40 @@ +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error + +# Fetch the Boston housing dataset from the original source +data_url = "http://lib.stat.cmu.edu/datasets/boston" +raw_df = pd.read_csv(data_url, sep=r"\s+", skiprows=22, header=None) +data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]]) +target = raw_df.values[1::2, 2] + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) + +# Create and train the linear regression model +model = LinearRegression() +model.fit(X_train, y_train) + +# Make predictions on the training and testing sets +y_train_pred = model.predict(X_train) +y_test_pred = model.predict(X_test) + +# Calculate the mean squared error for training and testing sets +train_mse = mean_squared_error(y_train, y_train_pred) +test_mse = mean_squared_error(y_test, y_test_pred) + +print("Train MSE:", train_mse) +print("Test MSE:", test_mse) + +# Plot residuals +plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data') +plt.scatter(y_test_pred, y_test_pred - y_test, c='green', marker='s', label='Test data') +plt.xlabel('Predicted values') +plt.ylabel('Residuals') +plt.legend(loc='upper left') +plt.hlines(y=0, xmin=min(y_train_pred.min(), y_test_pred.min()), xmax=max(y_train_pred.max(), y_test_pred.max()), color='red') +plt.title('Residuals plot') +plt.show() diff --git a/TASK-12.py b/TASK-12.py new file mode 100644 index 0000000..72eed63 --- /dev/null +++ b/TASK-12.py @@ -0,0 +1,66 @@ +from PIL import Image +import os + +def get_size_format(b, factor=1024, suffix="B"): + """ + Scale bytes to its proper byte format. + e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB' + """ + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if b < factor: + return f"{b:.2f}{unit}{suffix}" + b /= factor + return f"{b:.2f}Y{suffix}" + +def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): + try: + # Load the image into memory + img = Image.open(image_name) + + # Print the original image shape + print("[*] Image shape:", img.size) + + # Get the original image size in bytes + image_size = os.path.getsize(image_name) + print("[*] Size before compression:", get_size_format(image_size)) + + if width and height: + # If width and height are set, resize with them instead + img = img.resize((width, height), Image.LANCZOS) + elif new_size_ratio < 1.0: + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS) + + # Split the filename and extension + filename, ext = os.path.splitext(image_name) + + # Make a new filename appending "_compressed" to the original file name + if to_jpg: + # Change the extension to JPEG + new_filename = f"{filename}_compressed.jpg" + # Ensure image is in RGB mode for JPEG + if img.mode in ("RGBA", "LA"): + img = img.convert("RGB") + else: + # Retain the same extension of the original image + new_filename = f"{filename}_compressed{ext}" + + # Save the compressed image + img.save(new_filename, optimize=True, quality=quality) + + # Print the new image shape + print("[+] New Image shape:", img.size) + + # Get the new image size in bytes + new_image_size = os.path.getsize(new_filename) + print("[*] Size after compression:", get_size_format(new_image_size)) + print(f"[*] Compressed image saved as: {new_filename}") + + except FileNotFoundError: + print("Error: The file was not found.") + except OSError as e: + print(f"Error: {e}") + +# Example usage: +input_image = input("Enter the path to the image: ") +compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600) diff --git a/TASK-5.py b/TASK-5.py new file mode 100644 index 0000000..ee915c5 --- /dev/null +++ b/TASK-5.py @@ -0,0 +1,65 @@ +import requests +import datetime + +# Your OpenWeatherMap API key +API_KEY = '69e7dd8a8069d4066de2a18ea5996e36' +BASE_URL = 'http://api.openweathermap.org/data/2.5/' + +# Function to get current weather data +def get_current_weather(city): + url = f"{BASE_URL}weather?q={city}&appid={API_KEY}&units=metric" + response = requests.get(url) + return response.json() + +# Function to get weather forecast data +def get_forecast(city): + url = f"{BASE_URL}forecast?q={city}&appid={API_KEY}&units=metric" + response = requests.get(url) + return response.json() + +# Function to display weather data +def display_weather_data(city): + current_weather = get_current_weather(city) + forecast = get_forecast(city) + + if current_weather.get("cod") != 200 or forecast.get("cod") != "200": + print("Failed to retrieve data. Please check the city name or API key.") + return + + # Current weather + print(f"\nCurrent weather in {city.capitalize()}:") + print(f"Temperature: {current_weather['main']['temp']}°C") + print(f"Weather: {current_weather['weather'][0]['description']}") + print(f"Humidity: {current_weather['main']['humidity']}%") + print(f"Wind Speed: {current_weather['wind']['speed']} m/s") + + # Forecast + print(f"\n5-Day Forecast for {city.capitalize()}:") + for item in forecast['list']: + timestamp = item['dt'] + date_time = datetime.datetime.fromtimestamp(timestamp) + if date_time.hour == 12: # Show data for 12 PM each day + temp = item['main']['temp'] + weather = item['weather'][0]['description'] + print(f"{date_time.strftime('%Y-%m-%d %H:%M:%S')}: {temp}°C, {weather}") + + # Temperature trends (Average temperatures per day) + temp_trends = {} + for item in forecast['list']: + date = datetime.datetime.fromtimestamp(item['dt']).date() + if date not in temp_trends: + temp_trends[date] = [] + temp_trends[date].append(item['main']['temp']) + + print(f"\nTemperature Trends in {city.capitalize()}:") + for date, temps in temp_trends.items(): + avg_temp = sum(temps) / len(temps) + print(f"{date}: {avg_temp:.2f}°C") + +# Main function +def main(): + city = input("Enter the city name: ") + display_weather_data(city) + +if __name__ == "__main__": + main() diff --git a/TASK-6.py b/TASK-6.py new file mode 100644 index 0000000..c2551cf --- /dev/null +++ b/TASK-6.py @@ -0,0 +1,97 @@ +import requests +from bs4 import BeautifulSoup +import pandas as pd +import json +from urllib.parse import urljoin + +# Function to check robots.txt for scraping permission +def check_robots_txt(base_url): + robots_url = urljoin(base_url, '/robots.txt') + response = requests.get(robots_url) + if response.status_code == 200: + robots_txt = response.text + if "Disallow: /" in robots_txt: + return False + return True + return False + +# Function to list all tables in the HTML +def list_tables(soup): + tables = soup.find_all("table") + if not tables: + raise Exception("No tables found on the webpage.") + table_summaries = [] + for i, table in enumerate(tables): + summary = table.attrs.get("summary", f"Table {i+1}") + table_summaries.append(summary) + return tables, table_summaries + +# Function to extract data from the selected table +def extract_data(table): + data = [] + headers = [header.text.strip() for header in table.find_all("th")] + rows = table.find_all("tr")[1:] # Skipping the header row + for row in rows: + cells = row.find_all("td") + row_data = [cell.text.strip() for cell in cells] + data.append(row_data) + return headers, data + +# Main function to perform web scraping +def main(): + # Read the URL from the user + base_url = input("Enter the URL of the website to scrape: ") + + # Check if scraping is allowed + if not check_robots_txt(base_url): + print("It is not possible to perform web scraping on this website.") + return + + # Send a GET request to fetch the raw HTML content + response = requests.get(base_url) + if response.status_code != 200: + raise Exception(f"Failed to load page {base_url}") + + # Parse the content with BeautifulSoup + soup = BeautifulSoup(response.content, "html.parser") + + # List all tables + try: + tables, table_summaries = list_tables(soup) + except Exception as e: + print(f"Error during table listing: {e}") + return + + # Display the tables to the user and ask for a selection + print("Tables found on the webpage:") + for i, summary in enumerate(table_summaries): + print(f"{i + 1}: {summary}") + + try: + table_index = int(input("Enter the number of the table you want to scrape: ")) - 1 + if table_index < 0 or table_index >= len(tables): + raise ValueError("Invalid table number selected.") + except ValueError as e: + print(f"Error during table selection: {e}") + return + + # Extract data from the selected table + try: + headers, data = extract_data(tables[table_index]) + except Exception as e: + print(f"Error during data extraction: {e}") + return + + # Convert to DataFrame + df = pd.DataFrame(data, columns=headers) + + # Save to CSV + df.to_csv("scraped_data.csv", index=False) + + # Save to JSON + df.to_json("scraped_data.json", orient="records") + + print("Data has been scraped and saved to scraped_data.csv and scraped_data.json") + +if __name__ == "__main__": + main() diff --git a/TASK-7.py b/TASK-7.py new file mode 100644 index 0000000..143858c --- /dev/null +++ b/TASK-7.py @@ -0,0 +1,26 @@ +import nltk +from nltk.chat.util import Chat, reflections + +# Define pairs of patterns and responses +pairs = [ + (r'hi|hello|hey', ['Hello!', 'Hey there!', 'Hi! How can I help you?']), + (r'how are you?', ['I\'m doing well, thank you!', 'I\'m good, thanks for asking!']), + (r'what\'s your name\??', ['I\'m a chatbot!', 'You can call me ChatBot.']), + (r'(.*) your name\??', ['I\'m a chatbot!', 'You can call me ChatBot.']), + # Add more patterns and responses as needed +] + +# Create a Chatbot instance +chatbot = Chat(pairs, reflections) + +print("Welcome! Type 'quit' to end the conversation.") + +# Start the conversation loop +while True: + user_input = input("You: ") + if user_input.lower() == 'quit': + print("ChatBot: Bye! Have a great day!") + break + else: + response = chatbot.respond(user_input) + print("ChatBot:", response) diff --git a/TASK-8.py b/TASK-8.py new file mode 100644 index 0000000..7579a56 --- /dev/null +++ b/TASK-8.py @@ -0,0 +1,61 @@ + +import os +from PyPDF2 import PdfMerger, PdfReader, PdfWriter + +def merge_pdfs(pdf_list, output_path): + merger = PdfMerger() + + for pdf in pdf_list: + if os.path.exists(pdf): + merger.append(pdf) + else: + print(f"File not found: {pdf}") + + with open(output_path, 'wb') as output_file: + merger.write(output_file) + + print(f'Merged PDF saved as {output_path}') + +def split_pdf(input_path, output_folder): + if not os.path.exists(input_path): + print(f"File not found: {input_path}") + return + + with open(input_path, 'rb') as input_file: + reader = PdfReader(input_file) + num_pages = len(reader.pages) + + for page_num in range(num_pages): + writer = PdfWriter() + writer.add_page(reader.pages[page_num]) + + output_path = os.path.join(output_folder, f'page_{page_num + 1}.pdf') + with open(output_path, 'wb') as output_file: + writer.write(output_file) + + print(f'Saved {output_path}') + +def main(): + print("PDF Merger/Splitter") + print("1. Merge PDFs") + print("2. Split PDF") + print("3. Exit") + choice = input("Enter your choice: ") + + if choice == '1': + pdf_files = input("Enter the PDF files to merge (separated by commas): ").split(',') + pdf_files = [pdf.strip() for pdf in pdf_files] # Strip whitespace + output_path = input("Enter the output path for the merged PDF: ") + merge_pdfs(pdf_files, output_path) + elif choice == '2': + input_path = input("Enter the PDF file to split: ") + output_folder = input("Enter the output folder for the split PDFs: ") + os.makedirs(output_folder, exist_ok=True) + split_pdf(input_path, output_folder) + elif choice == '3': + print("Exiting.") + else: + print("Invalid choice. Exiting.") + +if __name__ == "__main__": + main() diff --git a/TASK-9.py b/TASK-9.py new file mode 100644 index 0000000..4ae7d87 --- /dev/null +++ b/TASK-9.py @@ -0,0 +1,37 @@ +from PIL import Image +import os + +def convert_image(input_path, output_path, output_format): + try: + # Open the image + with Image.open(input_path) as img: + # Check if the image has an alpha channel and convert it to RGB if necessary + if output_format == 'JPEG' and img.mode == 'RGBA': + img = img.convert('RGB') + + # Convert and save the image to the desired format + img.save(output_path, format=output_format) + print(f"Image converted successfully to {output_format} format.") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + input_path = input("Enter the path to the input image: ") + output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper() + + # Validate output format + if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']: + print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.") + return + + # Extract the file name and extension + file_name, file_extension = os.path.splitext(input_path) + + # Set the output path + output_path = f"{file_name}_converted.{output_format.lower()}" + + # Convert the image + convert_image(input_path, output_path, output_format) + +if __name__ == "__main__": + main() diff --git a/number guessing.py b/number guessing.py new file mode 100644 index 0000000..032c5dd --- /dev/null +++ b/number guessing.py @@ -0,0 +1,33 @@ +import random + +def guess_number(): + # Generate a random number between 1 and 100 + secret_number = random.randint(1, 100) + attempts = 0 + max_attempts = 10 + + print("Welcome to the Number Guessing Game!") + print("I have chosen a number between 1 and 100. You have", max_attempts, "attempts to guess it.") + + while attempts < max_attempts: + try: + guess = int(input("Enter your guess: ")) + except ValueError: + print("Invalid input! Please enter a valid number.") + continue + + attempts += 1 + + if guess < secret_number: + print("Too low! Try again.") + elif guess > secret_number: + print("Too high! Try again.") + else: + print("Congratulations! You've guessed the number", secret_number, "correctly in", attempts, "attempts!") + break + else: + print("Sorry, you've run out of attempts. The correct number was", secret_number) + +if __name__ == "__main__": + guess_number() + diff --git a/pdfconv.py b/pdfconv.py new file mode 100644 index 0000000..6b2aa9f --- /dev/null +++ b/pdfconv.py @@ -0,0 +1,90 @@ +import PyPDF2 +from PIL import Image +import os + +def convert_pdf_to_text(pdf_path, text_output_path): + """Converts a PDF file to text. + + Args: + pdf_path (str): Path to the input PDF file. + text_output_path (str): Path to save the converted text file. + """ + try: + with open(pdf_path, 'rb') as pdf_file: + pdf_reader = PyPDF2.PdfReader(pdf_file) + with open(text_output_path, 'w', encoding='utf-8') as text_file: + # Iterate through each page of the PDF + for page_num in range(len(pdf_reader.pages)): + page = pdf_reader.pages[page_num] + # Extract text from the page and write it to the text file + text_file.write(page.extract_text()) + print(f"PDF converted to text successfully. Text file saved at {text_output_path}") + except Exception as e: + print(f"An error occurred: {e}") + + +def extract_images_from_pdf(pdf_path, image_output_folder): + """Extracts images from a PDF file. + + Args: + pdf_path (str): Path to the input PDF file. + image_output_folder (str): Folder to save the extracted images. + """ + try: + with open(pdf_path, 'rb') as pdf_file: + pdf_reader = PyPDF2.PdfReader(pdf_file) + # Iterate through each page of the PDF + for page_num in range(len(pdf_reader.pages)): + page = pdf_reader.pages[page_num] + xObject = page.resources['XObject'].resolve() + for obj in xObject: + if xObject[obj]['/Subtype'] == '/Image': + size = (xObject[obj]['/Width'], xObject[obj]['/Height']) + data = xObject[obj].get_data() + mode = '' + if xObject[obj]['/ColorSpace'] == '/DeviceRGB': + mode = "RGB" + else: + mode = "P" + if xObject[obj]['/Filter'] == '/FlateDecode': + img = Image.frombytes(mode, size, data) + img.save(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.png")) + elif xObject[obj]['/Filter'] == '/DCTDecode': + img = open(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.jpg"), "wb") + img.write(data) + img.close() + elif xObject[obj]['/Filter'] == '/JPXDecode': + img = open(os.path.join(image_output_folder, f"page{page_num+1}_{obj[1:]}.jp2"), "wb") + img.write(data) + img.close() + print(f"Images extracted successfully. Saved in {image_output_folder}") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + # Get input paths and output folder from user + pdf_path = input("Enter the path to the PDF file: ") + output_folder = input("Enter the output folder path: ") + + # Create the output folder if it does not exist + if not os.path.exists(output_folder): + os.makedirs(output_folder) + + # Choose conversion option + choice = input("Choose an option:\n1. Convert PDF to text\n2. Extract images from PDF\nEnter your choice: ") + + if choice == '1': + # Convert PDF to text + text_output_path = os.path.join(output_folder, "converted_text.txt") + convert_pdf_to_text(pdf_path, text_output_path) + elif choice == '2': + # Extract images from PDF + image_output_folder = os.path.join(output_folder, "extracted_images") + if not os.path.exists(image_output_folder): + os.makedirs(image_output_folder) + extract_images_from_pdf(pdf_path, image_output_folder) + else: + print("Invalid choice. Please choose 1 or 2.") + +if __name__ == "__main__": + main() diff --git a/task1 b/task1 new file mode 100644 index 0000000..1422fc1 --- /dev/null +++ b/task1 @@ -0,0 +1,30 @@ +#a simple python program to perform basic tasks like addition,subtraction,multiplication,division +print('please select any of the number for performing arithmetic operations') +print("1.Addition") +print('2.Subtraction') +print('3.Multiplication') +print('4.Division') +print('5.exit') +a=int(input('Enter any of the number for performing arithmetic operations')) +def ari(a,var1,var2): + a,var1,var2=a,var1,var2 + if(a==1): + print(var1+var2) + if(a==2): + print(var1-var2) + if(a==3): + print(var1*var2) + if(a==4): + print(var1/var2) + return + +#Enter Two numbers +if((a>0) and (a<5)): + var1 = int(input('Enter First number: ')) + var2 = int(input('Enter Second number: ')) + ari(a,var1,var2) +elif(a==5): + exit() +else: + print('Invalid Option') + print('please select 1/2/3/4/5 only') \ No newline at end of file diff --git a/to_do_list.py b/to_do_list.py new file mode 100644 index 0000000..4766564 --- /dev/null +++ b/to_do_list.py @@ -0,0 +1,59 @@ +class TaskManager: + def __init__(self): + self.tasks = [] + + def add_task(self, task): + self.tasks.append({"task": task, "completed": False}) + + def delete_task(self, index): + if 0 <= index < len(self.tasks): + del self.tasks[index] + else: + print("Invalid task index") + + def mark_task_completed(self, index): + if 0 <= index < len(self.tasks): + self.tasks[index]["completed"] = True + else: + print("Invalid task index") + + def display_tasks(self): + print("Tasks:") + for i, task in enumerate(self.tasks): + status = "Completed" if task["completed"] else "Pending" + print(f"{i+1}. {task['task']} - {status}") + + +def main(): + task_manager = TaskManager() + + while True: + print("\nOptions:") + print("1. Add Task") + print("2. Delete Task") + print("3. Mark Task as Completed") + print("4. View Tasks") + print("5. Exit") + + choice = input("Enter your choice: ") + + if choice == "1": + task = input("Enter the task: ") + task_manager.add_task(task) + elif choice == "2": + index = int(input("Enter the index of the task to delete: ")) - 1 + task_manager.delete_task(index) + elif choice == "3": + index = int(input("Enter the index of the task to mark as completed: ")) - 1 + task_manager.mark_task_completed(index) + elif choice == "4": + task_manager.display_tasks() + elif choice == "5": + print("Exiting...") + break + else: + print("Invalid choice. Please try again.") + + +if __name__ == "__main__": + main()