Slip 16-30 WT And DA


Slip-16

Q. 1) Write Ajax program to get book details from XML file when user select a book name. Create XML
File for storing details of book(title, author, year, price).

Ans:

Xml file book_details.xml

<books> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> <price>10.99</price> </book> <book> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <year>1960</year> <price>8.99</price> </book> <book> <title>1984</title> <author>George Orwell</author> <year>1949</year> <price>6.99</price> </book> <book> <title>Pride and Prejudice</title> <author>Jane Austen</author> <year>1813</year> <price>7.99</price> </book> </books>

Ajax file

<!DOCTYPE html> <html> <head> <title>Book Details</title> <script src=https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js></script> <script> $(document).ready(function(){ $(“select”).change(function(){ Var book = $(this).val(); $.ajax({ url: “book_details.xml”, dataType: “xml”, success: function(xml){ $(xml).find(‘book’).each(function(){ Var title = $(this).find(‘title’).text(); If (title == book) { Var author = $(this).find(‘author’).text(); Var year = $(this).find(‘year’).text(); Var price = $(this).find(‘price’).text(); $(“#details”).html(“Author: “ + author + “<br>Year: “ + year + “<br>Price: “ + price); } }); } }); }); }); </script> </head> <body> <select> <option>Select a book</option> <option>The Great Gatsby</option> <option>To Kill a Mockingbird</option> <option>1984</option> <option>Pride and Prejudice</option> </select> <div id=”details”></div> </body> </html>

Q2).Consider any text paragraph. Preprocess the text to remove any special characters and digits.
Generate the summary using extractive summarization pprocess.
Ans:

Import re
Import nltk
From nltk.corpus import stopwords
From nltk.tokenize import sent_tokenize, word_tokenize
From heapq import nlargest

Sample text paragraph you can write any text

Text = “Natural language processing (NLP) is a subfield of linguistics, computer science, information engineering, and artificial intelligence concerned with the interactions between computers and human languages, in particular how to program computers to process and analyze large amounts of natural language data. Challenges in natural language processing frequently involve speech recognition, natural language understanding, and natural language generation. The history of natural language processing generally started in the 1950s, although work can be found from earlier periods.”

Remove special characters and digits

Text = re.sub(‘[^a-zA-Z]’, ‘ ‘, text)

Tokenize the text into sentences

Sentences = sent_tokenize(text)

Tokenize each sentence into words and remove stop words

Stop_words = set(stopwords.words(‘english’))
Words = []
For sentence in sentences:
Words.extend(word_tokenize(sentence))
Words = [word.lower() for word in words if word.lower() not in stop_words]

Calculate word frequency

Word_freq = nltk.FreqDist(words)

Calculate sentence scores based on word frequency

Sentence_scores = {}
For sentence in sentences:
For word in word_tokenize(sentence.lower()):
If word in word_freq:
If len(sentence.split(‘ ‘)) < 30:
If sentence not in sentence_scores:
Sentence_scores[sentence] = word_freq[word]
Else:
Sentence_scores[sentence] += word_freq[word]

Generate summary by selecting top 3 sentences with highest scores

Summary_sentences = nlargest(3, sentence_scores, key=sentence_scores.get)
Summary = ‘ ‘.join(summary_sentences)

Print(summary)

@Slip-17

Q. 1) Write a Java Script Program to show Hello Good Morning message onload event using alert box
And display the Student registration from.

Ans:

<!DOCTYPE html> <html> <head> <title>Student Registration Form</title> <script> Window.onload = function() { Alert(“Hello Good Morning!”); }; </script> </head> <body> <h1>Student Registration Form</h1> <form> <label for=”name”>Name:</label> <input type=”text” id=”name” name=”name” required><br><br> <label for=”email”>Email:</label> <input type=”email” id=”email” name=”email” required><br><br> <label for=”phone”>Phone:</label> <input type=”tel” id=”phone” name=”phone” required><br><br> <label for=”address”>Address:</label> <textarea id=”address” name=”address” required></textarea><br><br> <input type=”submit” value=”Submit”> </form> </body> </html>

Q. 2)Consider text paragraph.So, keep working. Keep striving. Never give up. Fall down seven times, get
Up eight. Ease is a greater threat to progress than hardship. Ease is a greater threat to progress than
Hardship. So, keep moving, keep growing, keep learning. See you at work.Preprocess the text to remove
Any special characters and digits. Generate the summary using extractive summarization process.
Ans:

Import re
From nltk.tokenize import sent_tokenize

Text paragraph

Text = “So, keep working. Keep striving. Never give up. Fall down seven times, get up eight. Ease is a greater threat to progress than hardship. Ease is a greater threat to progress than hardship. So, keep moving, keep growing, keep learning. See you at work.”

Remove special characters and digits

Text = re.sub(‘[^A-Za-z]+’, ‘ ‘, text)

Tokenize the sentences

Sentences = sent_tokenize(text)

Calculate the score of each sentence based on the number of words

The sentences with more words will have a higher score

Scores = {}
For sentence in sentences:
Words = sentence.split()
Score = len(words)
Scores[sentence] = score

Sort the sentences based on their scores

Sorted_sentences = sorted(scores.items(), key=lambda x: x[1], reverse=True)

Extract the top 2 sentences with the highest scores as the summary

Summary_sentences = [sentence[0] for sentence in sorted_sentences[:2]]
Summary = “ “.join(summary_sentences)

Print the summary

Print(summary)

@Slip-18

Q. 1) Write a Java Script Program to print Fibonacci numbers on onclick event.
Ans:

<!DOCTYPE html> <html> <head> <title>Fibonacci Numbers</title> <script> Function generateFibonacci() { // Get the input value from the user Var input = document.getElementById(“inputNumber”).value; Var output = document.getElementById(“output”);
		// Convert the input to a number
		Var n = parseInt(input);

		// Create an array to store the Fibonacci sequence
		Var fib = [];

		// Calculate the Fibonacci sequence up to n
		Fib[0] = 0;
		Fib[1] = 1;
		For (var i = 2; i <= n; i++) {
			Fib[i] = fib[i-1] + fib[i-2];
		}

		// Display the Fibonacci sequence
		Output.innerHTML = “Fibonacci sequence up to “ + n + “: “ + fib.join(“, “);
	}
</script>
</head> <body> <h1>Fibonacci Numbers</h1> <p>Enter a number:</p> <input type=”text” id=”inputNumber”> <button onclick=”generateFibonacci()”>Generate Fibonacci</button> <p id=”output”></p> </body> </html>

Q. 2)Consider any text paragraph. Remove the stopwords. Tokenize the paragraph to extract words and
Sentences. Calculate the word frequency distribution and plot the frequencies. Plot the wordcloud of the
Txt.

Ans:

Install the libraries

!pip install nltk matplotlib wordcloud

Import the necessary modules

Import nltk
From nltk.corpus import stopwords
From nltk.tokenize import word_tokenize, sent_tokenize
From nltk.probability import FreqDist
Import matplotlib.pyplot as plt
From wordcloud import WordCloud

Download the stopwords corpus

Nltk.download(‘stopwords’)

Define the text paragraph

Text = “Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tristique ante et velit vestibulum, vel pharetra orci iaculis. Nullam mattis risus quis augue tincidunt rhoncus. Morbi varius, arcu vitae scelerisque laoreet, magna est imperdiet quam, sit amet ultrices lectus justo id enim. Sed dictum suscipit commodo. Sed maximus consequat risus, nec pharetra nibh interdum quis. Etiam eget quam vel augue dictum dignissim sit amet nec elit. Nunc at sapien dolor. Nulla vitae iaculis lorem. Suspendisse potenti. Sed non ante turpis. Morbi consectetur, arcu a vestibulum suscipit, mauris eros convallis nibh, nec feugiat orci enim sit amet enim. Aliquam erat volutpat. Etiam vel nisi id neque viverra dapibus non non lectus.”

Tokenize the paragraph to extract words and sentences

Words = word_tokenize(text.lower())
Sentences = sent_tokenize(text)

Remove the stopwords from the extracted words

Stop_words = set(stopwords.words(‘english’))
Filtered_words = [word for word in words if word.casefold() not in stop_words]

Calculate the word frequency distribution and plot the frequencies using matplotlib

Fdist = FreqDist(filtered_words)
Fdist.plot(30, cumulative=False)
Plt.show()

Plot the wordcloud of the text using wordcloud

Wordcloud = WordCloud(width = 800, height = 800,
Background_color =’white’,
Stopwords = stop_words,
Min_font_size = 10).generate(text)

plot the WordCloud image

Plt.figure(figsize = (8, 8), facecolor = None)
Plt.imshow(wordcloud)
Plt.axis(“off”)
Plt.tight_layout(pad = 0)

Plt.show()

@Slip-19

Q. 1) Write a Java Script Program to validate user name and password on onSubmit event.
Ans:

<!DOCTYPE html> <html> <head> <title>Validate User Name and Password</title> <script> Function validateForm() { Var username = document.forms[“myForm”][“username”].value; Var password = document.forms[“myForm”][“password”].value;
    If (username == “”) {
      Alert(“Username must be filled out”);
      Return false;
    }

    If (password == “”) {
      Alert(“Password must be filled out”);
      Return false;
    }
  }
</script>
</head> <body> <h2>Validate User Name and Password</h2> <form name=”myForm” onsubmit=”return validateForm()” method=”post”> <label for=”username”>Username:</label> <input type=”text” id=”username” name=”username”><br><br> <label for=”password”>Password:</label> <input type=”password” id=”password” name=”password”><br><br> <input type=”submit” value=”Submit”> </form> </body> </html>

Q. 2)Download the movie_review.csv dataset from Kaggle by using the following link
:https://www.kaggle.com/nltkdata/movie-review/version/3?select=movie_review.csv to perform
Sentiment analysis on above dataset and create a wordcloud.

Ans:

Import pandas as pd
From textblob import TextBlob
From wordcloud import WordCloud, STOPWORDS
Import matplotlib.pyplot as plt

Load the dataset

Df = pd.read_csv(‘movie_review.csv’)

Add a column for sentiment analysis using TextBlob

Df[‘Sentiment’] = df[‘Review’].apply(lambda x: TextBlob(x).sentiment.polarity)

Create a new dataframe for positive reviews only

Pos_df = df[df[‘Sentiment’] > 0.2]

Create a wordcloud for positive reviews

Wordcloud = WordCloud(width = 800, height = 800,
Background_color =’white’,
Stopwords = STOPWORDS,
Min_font_size = 10).generate(‘ ‘.join(pos_df[‘Review’]))

Plot the wordcloud

Plt.figure(figsize = (8, 8), facecolor = None)
Plt.imshow(wordcloud)
Plt.axis(“off”)
Plt.tight_layout(pad = 0)

Plt.show()

@Slip-20

Q. 1) create a student.xml file containing at least 5 student information.
Ans:

<?xml version=”1.0”?> <students> <student> <name>John Doe</name> <age>21</age> <gender>Male</gender> <major>Computer Science</major> <gpa>3.8</gpa> </student> <student> <name>Jane Smith</name> <age>19</age> <gender>Female</gender> <major>Business</major> <gpa>3.5</gpa> </student> <student> <name>Tom Johnson</name> <age>20</age> <gender>Male</gender> <major>Engineering</major> <gpa>3.2</gpa> </student> <student> <name>Sara Lee</name> <age>22</age> <gender>Female</gender> <major>Psychology</major> <gpa>3.6</gpa> </student> <student> <name>Mike Brown</name> <age>18</age> <gender>Male</gender> <major>Education</major> <gpa>3.4</gpa> </student> </students>

Q. 2)Consider text paragraph.”””Hello all, Welcome to Python Programming Academy. Python
Programming Academy is a nice platform to learn new programming skills. It is difficult to get enrolled
In this Academy.”””Remove the stopwords.
Ans:

Import nltk
From nltk.corpus import stopwords
Nltk.download(‘stopwords’)

Text paragraph

Text = “Hello all, Welcome to Python Programming Academy. Python Programming Academy is a nice platform to learn new programming skills. It is difficult to get enrolled in this Academy.”

Tokenize the text

Tokens = nltk.word_tokenize(text)

Remove stopwords

Stop_words = set(stopwords.words(‘english’))
Filtered_tokens = [word for word in tokens if not word.lower() in stop_words]

Print the filtered tokens

Print(filtered_tokens)

@Slip-21

Q. 1)Add a JavaScript File in Codeigniter. The Javascript code should check whether a number is
Positive or negative.

Ans:

Html file

<!DOCTYPE html> <html> <head> <title>Number Check</title> <script src=”<?php echo base_url(‘js/numberCheck.js’); ?>”></script> </head> <body> <h1>Number Check</h1> <p>Enter a number to check:</p> <input type=”number” id=”num” /> <button onclick=”checkNumber(document.getElementById(‘num’).value)”>Check</button> </body> </html>

Create is file check number.js

Function checkNumber(num) {
If (num > 0) {
Alert(“The number is positive.”);
} else if (num < 0) {
Alert(“The number is negative.”);
} else {
Alert(“The number is zero.”);
}
}

Q. 2)Build a simple linear regression model for User Data.
Ans:
Import pandas as pd
From sklearn.model_selection import train_test_split
From sklearn.linear_model import LinearRegression
From sklearn.metrics import mean_squared_error, r2_score
Import matplotlib.pyplot as plt

1. Collect data

Data = pd.read_csv(‘user_data.csv’)

2. Preprocess data

Data.dropna(inplace=True)
X = data[‘age’].values.reshape(-1, 1)
Y = data[‘income’].values.reshape(-1, 1)

3. Split data

X_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

4. Train the model

Regressor = LinearRegression()
Regressor.fit(x_train, y_train)

5. Predict values

Y_pred = regressor.predict(x_test)

6. Evaluate model

Mse = mean_squared_error(y_test, y_pred)
R2 = r2_score(y_test, y_pred)
Print(“Mean squared error: “, mse)
Print(“R-squared: “, r2)

7. Visualize results

Plt.scatter(x_test, y_test, color=’gray’)
Plt.plot(x_test, y_pred, color=’red’, linewidth=2)
Plt.show()

@Slip-22

Q. 1)Create a table student having attributes(rollno, name, class). Using codeigniter, connect to the
Database and insert 5 recodes in it.

Ans:

<?php // Establish connection to PostgreSQL database $conn = pg_connect(“host=localhost dbname=your_database_name user=your_username password=your_password”); // Check if connection was successful If (!$conn) { Echo “Connection failed.”; Exit; } // Create student table $query = “CREATE TABLE student ( Rollno INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL, Class VARCHAR(10) NOT NULL )”; $result = pg_query($conn, $query); If (!$result) { Echo “Error creating table: “ . pg_last_error($conn); Exit; } else { Echo “Table created successfully.<br>”; } // Insert 5 records into student table $insert_query = “INSERT INTO student (rollno, name, class) VALUES (1, ‘John Doe’, ‘10A’), (2, ‘Jane Smith’, ‘9B’), (3, ‘Bob Johnson’, ‘11C’), (4, ‘Sarah Lee’, ‘12D’), (5, ‘Tom Brown’, ‘8E’)”; $insert_result = pg_query($conn, $insert_query); If (!$insert_result) { Echo “Error inserting records: “ . pg_last_error($conn); Exit; } else { Echo “Records inserted successfully.”; } // Close database connection Pg_close($conn); ?>

Q2).Consider any text paragraph. Remove the stopwords.
Ans:

Import nltk
From nltk.corpus import stopwords
From nltk.tokenize import word_tokenize

sample text paragraph

Text = “Hello all, Welcome to Python Programming Academy. Python Programming Academy is a nice platform to learn new programming skills. It is difficult to get enrolled in this Academy.”

tokenize the text paragraph

Words = word_tokenize(text)

define stopwords

Stop_words = set(stopwords.words(‘english’))

remove stopwords

Filtered_words = [word for word in words if word.casefold() not in stop_words]

join filtered words to form a sentence

Filtered_sentence = ‘ ‘.join(filtered_words)

Print(filtered_sentence)

@Slip-23

Q. 1) Create a table student having attributes(rollno, name, class) containing atleast 5 recodes . Using
Codeigniter, display all its records.

Ans:

<?php // Establish connection to PostgreSQL database $conn = pg_connect(“host=localhost dbname=your_database_name user=your_username password=your_password”); // Check if connection was successful If (!$conn) { Echo “Connection failed.”; Exit; } // Create student table $query = “CREATE TABLE student ( Rollno INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL, Class VARCHAR(10) NOT NULL )”; $result = pg_query($conn, $query); If (!$result) { Echo “Error creating table: “ . pg_last_error($conn); Exit; } else { Echo “Table created successfully.<br>”; } // Insert 5 records into student table $insert_query = “INSERT INTO student (rollno, name, class) VALUES (1, ‘John Doe’, ‘10A’), (2, ‘Jane Smith’, ‘9B’), (3, ‘Bob Johnson’, ‘11C’), (4, ‘Sarah Lee’, ‘12D’), (5, ‘Tom Brown’, ‘8E’)”; $insert_result = pg_query($conn, $insert_query); If (!$insert_result) { Echo “Error inserting records: “ . pg_last_error($conn); Exit; } else { Echo “Records inserted successfully.”; } // Close database connection Pg_close($conn); // function to display database records Function display_records($table_name) { // establish connection to PostgreSQL database $conn = pg_connect(“host=localhost dbname=your_database_name user=your_username password=your_password”); // check if connection was successful If (!$conn) { Echo “Connection failed.”; Exit; } // retrieve records from specified table $query = “SELECT * FROM “ . $table_name; $result = pg_query($conn, $query); // check if query was successful If (!$result) { Echo “Error retrieving records: “ . pg_last_error($conn); Exit; } // display records in an HTML table Echo “<table>”; Echo “<tr><th>Roll No</th><th>Name</th><th>Class</th></tr>”; While ($row = pg_fetch_assoc($result)) { Echo “<tr><td>” . $row[‘rollno’] . “</td><td>” . $row[‘name’] . “</td><td>” . $row[‘class’] . “</td></tr>”; } Echo “</table>”; // close database connection Pg_close($conn); } ?>

Q2).Consider any text paragraph. Preprocess the text to remove any special characters and
Digits.

Ans:

Import re

Text = “Hello, #world123! This is a sample text paragraph. It contains special characters and 5 digits.”

Remove special characters and digits

Processed_text = re.sub(r’[^a-zA-Z\s]’, ‘’, text)

Print(processed_text)

@Slip-24

Q. 1) Write a PHP script to create student.xml file which contains student roll no, name, address, college
And course. Print students detail of specific course in tabular format after accepting course as input.

Ans:

<?php // Define student details $students = array( Array(“rollno” => 1, “name” => “John Doe”, “address” => “123 Main St”, “college” => “AB