Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 29, 2024. It is now read-only.

Commit 556c181

Browse files
Task Completed
Task Completed
1 parent b5be041 commit 556c181

File tree

4 files changed

+195
-0
lines changed

4 files changed

+195
-0
lines changed

‎Arjun Parasar/Chatbot/chatbot.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import nltk
2+
from nltk.chat.util import Chat, reflections
3+
4+
pairs = [
5+
['hi|hello|hey', ['Hello!', 'Hi there!', 'Hey!']],
6+
['how are you?', ['I am doing well, thank you!', 'I am good, thanks for asking!']],
7+
['what is your name?', ['I am just a chatbot.', 'I am a chatbot designed to assist you.']],
8+
['what can you do?', ['I can provide information on various topics. Feel free to ask me anything!']],
9+
['bye|goodbye', ['Goodbye!', 'Bye! Have a great day!']],
10+
['(.*) weather (.*)', ['Sorry, I cannot provide weather information at the moment.']],
11+
['(.*) news (.*)', ['I am not able to provide news updates right now.']],
12+
['(.*) time (.*)', ['Sorry, I cannot provide time information currently.']]
13+
]
14+
15+
chat = Chat(pairs, reflections)
16+
17+
def chat_respond(user_input):
18+
return chat.respond(user_input)
19+
20+
def main():
21+
print("Hello! I'm a simple chatbot.")
22+
23+
while True:
24+
user_input = input("You : ")
25+
response = chat_respond(user_input)
26+
print("Bot:",response)
27+
if user_input.lower() == 'bye':
28+
break
29+
30+
if __name__ == "__main__":
31+
main()
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import requests
2+
import matplotlib.pyplot as plt
3+
import datetime
4+
5+
# Function to fetch current weather data from Open-Meteo API
6+
def fetch_weather_data(lat, lon):
7+
current_weather_url = f'https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true'
8+
forecast_url = f'https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&hourly=temperature_2m&daily=temperature_2m_max,temperature_2m_min&timezone=auto'
9+
10+
current_weather_response = requests.get(current_weather_url)
11+
current_weather_response.raise_for_status() # Raise an exception for HTTP errors
12+
13+
forecast_response = requests.get(forecast_url)
14+
forecast_response.raise_for_status() # Raise an exception for HTTP errors
15+
16+
return current_weather_response.json(), forecast_response.json()
17+
18+
# Function to display current weather data
19+
def display_current_weather(weather_data):
20+
current_weather = weather_data['current_weather']
21+
print("Current weather:")
22+
print(f"Temperature: {current_weather['temperature']}°C")
23+
print(f"Windspeed: {current_weather['windspeed']} km/h")
24+
print(f"Wind direction: {current_weather['winddirection']}°")
25+
print()
26+
27+
# Function to display forecast data
28+
def display_forecast(forecast_data):
29+
daily_forecast = forecast_data['daily']
30+
dates = daily_forecast['time']
31+
max_temps = daily_forecast['temperature_2m_max']
32+
min_temps = daily_forecast['temperature_2m_min']
33+
34+
print("5-day forecast:")
35+
for date, max_temp, min_temp in zip(dates, max_temps, min_temps):
36+
print(f"{date}: Max Temp: {max_temp}°C, Min Temp: {min_temp}°C")
37+
print()
38+
39+
# Function to parse datetime with optional seconds
40+
def parse_datetime(date_str):
41+
for fmt in ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M'):
42+
try:
43+
return datetime.datetime.strptime(date_str, fmt)
44+
except ValueError:
45+
continue
46+
raise ValueError(f"Date format for '{date_str}' not recognized")
47+
48+
# Function to plot temperature trends
49+
def plot_temperature_trends(forecast_data):
50+
hourly_forecast = forecast_data['hourly']
51+
times = hourly_forecast['time']
52+
temperatures = hourly_forecast['temperature_2m']
53+
54+
dates = [parse_datetime(time) for time in times]
55+
56+
plt.figure(figsize=(10, 5))
57+
plt.plot(dates, temperatures, marker='o')
58+
plt.title('Temperature Trends')
59+
plt.xlabel('Date')
60+
plt.ylabel('Temperature (°C)')
61+
plt.grid(True)
62+
plt.show()
63+
64+
# Function to get latitude and longitude from user input
65+
def get_location_coordinates(location):
66+
geocoding_url = f'https://geocoding-api.open-meteo.com/v1/search?name={location}'
67+
response = requests.get(geocoding_url)
68+
response.raise_for_status() # Raise an exception for HTTP errors
69+
70+
data = response.json()
71+
if data['results']:
72+
return data['results'][0]['latitude'], data['results'][0]['longitude']
73+
else:
74+
raise ValueError("Location not found")
75+
76+
# Main function to fetch and display weather data
77+
def main():
78+
location = input("Enter the location (e.g., London): ")
79+
try:
80+
lat, lon = get_location_coordinates(location)
81+
current_weather, forecast = fetch_weather_data(lat, lon)
82+
83+
display_current_weather(current_weather)
84+
display_forecast(forecast)
85+
plot_temperature_trends(forecast)
86+
except requests.exceptions.HTTPError as http_err:
87+
print(f"HTTP error occurred: {http_err}")
88+
except ValueError as val_err:
89+
print(f"Error: {val_err}")
90+
except Exception as err:
91+
print(f"An error occurred: {err}")
92+
93+
if __name__ == "__main__":
94+
main()
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from PyPDF2 import PdfReader, PdfWriter
2+
import os
3+
4+
def split_pdf(input_pdf_path, output_folder):
5+
pdf_reader = PdfReader(input_pdf_path)
6+
7+
for page_num in range(len(pdf_reader.pages)):
8+
pdf_writer = PdfWriter()
9+
pdf_writer.add_page(pdf_reader.pages[page_num])
10+
11+
output_pdf_path = os.path.join(output_folder, f'page_{page_num + 1}.pdf')
12+
13+
with open(output_pdf_path, 'wb') as out:
14+
pdf_writer.write(out)
15+
print(f'Page {page_num + 1} saved to {output_pdf_path}')
16+
17+
def main():
18+
input_path = input("Enter the path of the PDF file to split: ").strip()
19+
output_folder = input("Enter the output folder path: ").strip()
20+
21+
split_pdf(input_path, output_folder)
22+
23+
if __name__ == "__main__":
24+
main()
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import requests
2+
from bs4 import BeautifulSoup
3+
import pandas as pd
4+
5+
# Define the URL of the website to scrape
6+
url = "http://books.toscrape.com/"
7+
8+
# Send a GET request to the website
9+
response = requests.get(url)
10+
11+
# Check if the request was successful
12+
if response.status_code == 200:
13+
# Parse the HTML content using BeautifulSoup
14+
soup = BeautifulSoup(response.content, 'html.parser')
15+
16+
# Find the container with the list of books
17+
books_container = soup.find_all('article', class_='product_pod')
18+
19+
# Create lists to store the data
20+
titles = []
21+
prices = []
22+
availability = []
23+
24+
# Loop through the container and extract data
25+
for book in books_container:
26+
title = book.h3.a['title']
27+
price = book.find('p', class_='price_color').text
28+
availability_status = book.find('p', class_='instock availability').text.strip()
29+
30+
titles.append(title)
31+
prices.append(price)
32+
availability.append(availability_status)
33+
34+
# Create a DataFrame using pandas
35+
books_df = pd.DataFrame({
36+
'Title': titles,
37+
'Price': prices,
38+
'Availability': availability
39+
})
40+
41+
# Save the DataFrame to a CSV file
42+
books_df.to_csv('books.csv', index=False)
43+
44+
print("Data has been successfully scraped and saved to books.csv")
45+
else:
46+
print(f"Failed to retrieve the webpage. Status code: {response.status_code}")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /