0% found this document useful (0 votes)
3 views12 pages

DW - DW Internal 1 - Merged

The document contains multiple experiments and programs demonstrating various data handling techniques in Python, including file operations, CSV and JSON handling, XML parsing, Excel data manipulation, SQLite database interactions, and data visualization using libraries like Matplotlib and Pygal. Each experiment showcases different functionalities such as writing and reading student details, extracting text from PDFs, and generating maps to visualize child labor statistics. Overall, it serves as a comprehensive guide to practical applications of Python in data management and visualization.

Uploaded by

mukeshbalaga2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

DW - DW Internal 1 - Merged

The document contains multiple experiments and programs demonstrating various data handling techniques in Python, including file operations, CSV and JSON handling, XML parsing, Excel data manipulation, SQLite database interactions, and data visualization using libraries like Matplotlib and Pygal. Each experiment showcases different functionalities such as writing and reading student details, extracting text from PDFs, and generating maps to visualize child labor statistics. Overall, it serves as a comprehensive guide to practical applications of Python in data management and visualization.

Uploaded by

mukeshbalaga2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Experiment – 1

def write_to_file(filename):

with open(filename, "w") as file:

num_students = int(input("Enter the number of students: "))

for _ in range(num_students):

name = input("Enter student name: ")

roll_no = input("Enter roll no: ")

marks = float(input("Enter marks: "))

file.write(f"{name},{roll_no},{marks}\n")

print(f"\nData saved successfully to {filename}.\n")

def read_from_file(filename):

print("\nStudent Details:")

with open(filename, "r") as file:

for line in file:

name, roll_no, marks = line.strip().split(",")

print(f"Name: {name}, Roll number: {roll_no}, Marks: {marks}")

def main():

filename = "students.csv"

while True:

print("\n--- Student Marks Management ---")

print("1. Write student details")

print("2. Read student details")

print("3. Exit")

choice = input("Enter your choice: ")

if choice == "1":

write_to_file(filename)

elif choice == "2":

read_from_file(filename)

elif choice == "3": else:

print("Exiting program") print("Invalid choice! Please try again.")

break main()
Experiment – 2
import csv

def read_csv_as_dict(filename):
try:
with open(filename, mode='r') as file:
csv_reader = csv.DictReader(file)
print("\nCSV File Contents:")
for row in csv_reader:
print(dict(row))
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")

def main():
filename = input("Enter the CSV file name (with .csv extension): ")
read_csv_as_dict(filename)

main()
Experiment – 3

import json

# Data to write
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}

# Writing to a JSON file


with open('data.json', mode='w') as file:
json.dump(data, file, indent=4) # 'indent=4' makes the file readable
Experiment – 4

import xml.etree.ElementTree as ET

# Parse the XML file


tree = ET.parse("new.xml")
root = tree.getroot()

# Extract and print employee details


for employee in root.findall('employee'):
name = employee.find('name').text
age = employee.find('age').text
print(f"Name: {name}, Age: {age}")
Experiment – 5

import pandas as pd
import numpy as np

# Import the Excel file into a Pandas DataFrame


file_path = 'child.xlsx' # Replace with your file path
df = pd.read_excel(file_path)

# a. Get the data types of the given Excel data


print("Data Types of Each Column:")
print(df.dtypes)

# b. Display the last five rows


print("\nLast 5 Rows of the DataFrame:")
print(df.tail(5))

# c. Insert a column in the sixth position and fill it with NaN values
#df.insert(5, 'New_Column', np.nan) # Index 5 corresponds to the 6th column
print("\nDataFrame After Adding New Column:")
print(df.head()) # Display the first few rows to confirm the new column

# Optional: Save the modified DataFrame to a new Excel file


output_file_path = 'childcsd.xlsx'
df.to_excel(output_file_path, index=False)
print(f"\nModified DataFrame saved to {output_file_path}")
Experiment – 6

from pdfminer.high_level import extract_text

# Extract text from a PDF file


text = extract_text("task1.pdf")

# Print the extracted text


print(text)
Program 7

import pandas as pd

file_path = "child7exp.xlsx"

xls = pd.ExcelFile(file_path)

print("Available Sheets:", xls.sheet_names)

for sheet in xls.sheet_names:

df = pd.read_excel(xls, sheet_name=sheet)

print(f"\nData from Sheet: {sheet}")

print(df.head()) # Show first 5 rows

output_csv = f"{sheet}.csv"

df.to_csv(output_csv, index=False)

print(f"Saved {sheet} data as {output_csv}")


Program 8

import sqlite3

conn = sqlite3.connect('mydatabase.db')

cursor = conn.cursor()

cursor.execute("""

CREATE TABLE IF NOT EXISTS salesman (

salesman_id INTEGER,

name TEXT,

city TEXT,

commission REAL

);

""")

s_id = input('Salesman ID: ')

s_name = input('Name: ')

s_city = input('City: ')

s_commission = float(input('Commission: ')) # Convert commission to float

try:

cursor.execute("""

INSERT INTO salesman (salesman_id, name, city, commission)

VALUES (?, ?, ?, ?)

""", (s_id, s_name, s_city, s_commission))

conn.commit() # Commit the transaction

print('Data entered successfully.')

except sqlite3.Error as e:

print(f'An error occurred: {e}')

finally:

conn.close() # Close the connection

print("\nThe SQLite connection is closed.")


Program 10

import agate

table = agate.Table.from_csv('data10.csv')

print("Table Columns:")

print([column.name for column in table.columns])

print("\nFirst 5 Rows of the Table:")

table.print_table(max_rows=5)

print("\nSummary Statistics:")

for column in table.columns:

if isinstance(column.data_type, agate.Number):

print(f"{column.name}:")

print(f" Mean: {table.aggregate(agate.Mean(column.name))}")

print(f" Median: {table.aggregate(agate.Median(column.name))}")

print(f" Max: {table.aggregate(agate.Max(column.name))}")

print(f" Min: {table.aggregate(agate.Min(column.name))}")

col1 = 'CPI 2013 Score'

col2 = 'Total (%)'

from scipy.stats import pearsonr

col1 = [float(value) for value in table.columns['CPI 2013 Score'] if isinstance(value, (int, float))]

col2 = [float(value) for value in table.columns['Total (%)'] if isinstance(value, (int, float))]

print(table.columns['CPI 2013 Score'])

print(table.columns['Total (%)'])
Program 11

import matplotlib.pyplot as plt

# pip install matplotlib

# Sample dataset: CPI 2013 Scores vs Child Labor Percentages

data = [

{'Country': 'Country A', 'CPI 2013 Score': 90, 'Total (%)': 5},

{'Country': 'Country B', 'CPI 2013 Score': 80, 'Total (%)': 15},

{'Country': 'Country C', 'CPI 2013 Score': 70, 'Total (%)': 25},

# Extracting data for plotting

cpi_scores = [item['CPI 2013 Score'] for item in data]

child_labour_percentages = [item['Total (%)'] for item in data]

countries = [item['Country'] for item in data]

# Creating the scatter plot

plt.figure(figsize=(10, 6))

plt.scatter(cpi_scores, child_labour_percentages, color='blue')

# Annotate points with country names

for i, country in enumerate(countries):

plt.annotate(country, (cpi_scores[i], child_labour_percentages[i]))

# Adding titles and labels

plt.xlabel('CPI Score - 2013')

plt.ylabel('Child Labour Percentage (%)')

plt.title('CPI & Child Labor Correlation')

plt.grid(True)

plt.show()
Program 12

import pygal

from pygal.style import Style

custom_style = Style(

background='white',

plot_background='white',

foreground='black',

foreground_strong='black',

foreground_subtle='gray',

colors=('#E88080', '#404040', '#9BCB50')

child_labour_data = {

'in': 10, # India

'pk': 12, # Pakistan

'bd': 15, # Bangladesh

'ng': 25, # Nigeria

'cn': 5, # China

'us': 1, # United States

'br': 7, # Brazil

'za': 8, # South Africa

'et': 30, # Ethiopia

'eg': 15 # Egypt

worldmap = pygal.maps.world.World(style=custom_style)

worldmap.title = 'Child Labour Worldwide (%)'

worldmap.add('Child Labour (%)', child_labour_data)

worldmap.render_to_file('world.svg')

print("World map has been saved as 'world.svg'.")


Program 13

import requests

# Fetch the robots.txt file from Wikipedia

response = requests.get("https://en.wikipedia.org/robots.txt")

test = response.text

# Display the content

print("robots.txt for http://www.wikipedia.org/")

print("=" * 60)

print(test)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy