diff --git a/Ch4 - Dates and Times/calendars_finished.py b/Ch4 - Dates and Times/calendars_finished.py index 1372384..1029536 100644 --- a/Ch4 - Dates and Times/calendars_finished.py +++ b/Ch4 - Dates and Times/calendars_finished.py @@ -8,43 +8,43 @@ # create a plain text calendar c = calendar.TextCalendar(calendar.SUNDAY) -str = c.formatmonth(2022, 1, 0, 0) -print (str) +# str = c.formatmonth(2022, 1, 0, 0) +# print (str) # create an HTML formatted calendar -hc = calendar.HTMLCalendar(calendar.SUNDAY) -str = hc.formatmonth(2022, 1) -print (str) +# hc = calendar.HTMLCalendar(calendar.SUNDAY) +# str = hc.formatmonth(2022, 1) +# print (str) -# loop over the days of a month -# zeroes mean that the day of the week is in an overlapping month +# # loop over the days of a month +# # zeroes mean that the day of the week is in an overlapping month for i in c.itermonthdays(2022, 8): print (i) -# The Calendar module provides useful utilities for the given locale, -# such as the names of days and months in both full and abbreviated forms -for name in calendar.month_name: - print (name) +# # The Calendar module provides useful utilities for the given locale, +# # such as the names of days and months in both full and abbreviated forms +# for name in calendar.month_name: +# print (name) for day in calendar.day_name: print (day) -# Calculate days based on a rule: For example, consider -# a team meeting on the first Friday of every month. -# To figure out what days that would be for each month, -# we can use this script: -print ("Team meetings will be on:") -for m in range(1,13): - # returns an array of weeks that represent the month - cal = calendar.monthcalendar(2022, m) - # The first Friday has to be within the first two weeks - weekone = cal[0] - weektwo = cal[1] +# # Calculate days based on a rule: For example, consider +# # a team meeting on the first Friday of every month. +# # To figure out what days that would be for each month, +# # we can use this script: +# print ("Team meetings will be on:") +# for m in range(1,13): +# # returns an array of weeks that represent the month +# cal = calendar.monthcalendar(2022, m) +# # The first Friday has to be within the first two weeks +# weekone = cal[0] +# weektwo = cal[1] - if weekone[calendar.FRIDAY] != 0: - meetday = weekone[calendar.FRIDAY] - else: - # if the first friday isn't in the first week, it must be in the second - meetday = weektwo[calendar.FRIDAY] +# if weekone[calendar.FRIDAY] != 0: +# meetday = weekone[calendar.FRIDAY] +# else: +# # if the first friday isn't in the first week, it must be in the second +# meetday = weektwo[calendar.FRIDAY] - print ("%10s %2d" % (calendar.month_name[m], meetday)) +# print ("%10s %2d" % (calendar.month_name[m], meetday)) diff --git a/Ch4 - Dates and Times/calendars_start.py b/Ch4 - Dates and Times/calendars_start.py index 2963f70..72c0447 100644 --- a/Ch4 - Dates and Times/calendars_start.py +++ b/Ch4 - Dates and Times/calendars_start.py @@ -5,13 +5,22 @@ # TODO: import the calendar module - +import calendar +from datetime import datetime # TODO: create a plain text calendar +# year = datetime.now().year +# month = datetime.now().month +# c = calendar.monthcalendar(year, month) +# # print(c) +# print(len([i for i in calendar.monthcalendar(year, month)])) # TODO: create an HTML formatted calendar - +# today = datetime.today() +# days=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] +# print(today.weekday()) +# print("Tomorrow will be "+days[(today.weekday()+1)]) # TODO: loop over the days of a month # zeroes mean that the day of the week is in an overlapping month @@ -26,3 +35,10 @@ # To figure out what days that would be for each month, # we can use this script: +import calendar +import datetime +year = datetime.datetime.now().year +cal = calendar.TextCalendar(calendar.SUNDAY) +print(cal.formatmonth(year,1,0,0)) +# for m in range(1,13): +# print(cal.formatmonth(year, m, 0, 0)) \ No newline at end of file diff --git a/Ch4 - Dates and Times/dates_start.py b/Ch4 - Dates and Times/dates_start.py index 9091c40..8f96169 100644 --- a/Ch4 - Dates and Times/dates_start.py +++ b/Ch4 - Dates and Times/dates_start.py @@ -3,15 +3,18 @@ # LinkedIn Learning Python course by Joe Marini # - +from datetime import date +from datetime import time +from datetime import datetime def main(): ## DATE OBJECTS # TODO: Get today's date from the simple today() method from the date class - + today = date.today() + print ("Today's date is", today) # TODO: print out the date's individual components - + print("Date components:", today.day, today.month, today.year) # TODO: retrieve today's weekday (0=Monday, 6=Sunday) diff --git a/Ch4 - Dates and Times/formatting_start.py b/Ch4 - Dates and Times/formatting_start.py index 6c40839..5a6229f 100644 --- a/Ch4 - Dates and Times/formatting_start.py +++ b/Ch4 - Dates and Times/formatting_start.py @@ -9,20 +9,24 @@ def main(): # Times and dates can be formatted using a set of predefined string # control codes - + now = datetime.now() #### Date Formatting #### # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month - + print(now.strftime("The current year is: %Y")) + print(now.strftime("%A, %d %b, %Y")) # %c - locale's date and time, %x - locale's date, %X - locale's time - + print(now.strftime("Locale date and time: %c")) + print(now.strftime("Locale date: %x")) + print(now.strftime("Locale time: %X")) #### Time Formatting #### # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM - + print (now.strftime("Current time: %I:%M:%S %p")) # 12-Hour:Minute:Second:AM + print (now.strftime("24-hour time: %H:%M")) # 24-Hour:Minute if __name__ == "__main__": main() diff --git a/Ch4 - Dates and Times/timedeltas_start.py b/Ch4 - Dates and Times/timedeltas_start.py index a6b62bc..d3ecf46 100644 --- a/Ch4 - Dates and Times/timedeltas_start.py +++ b/Ch4 - Dates and Times/timedeltas_start.py @@ -7,29 +7,37 @@ from datetime import date from datetime import time from datetime import datetime +from datetime import timedelta # TODO: construct a basic timedelta and print it - +print (timedelta(days=365, hours=5, minutes=1)) # TODO: print today's date +now = datetime.now() +print("Today is", now) +# print today's date one year from now +print ("one year from now it will be: " + str(now + timedelta(days=365))) -# TODO: print today's date one year from now - - -# TODO: create a timedelta that uses more than one argument - - -# TODO: calculate the date 1 week ago, formatted as a string +# create a timedelta that uses more than one argument +print ("in two weeks and 3 days it will be: " + str(now + timedelta(weeks=2, days=3))) +# calculate the date 1 week ago, formatted as a string +t = datetime.now() - timedelta(weeks=1) +s = t.strftime("%A %B %d, %Y") +print ("one week ago it was " + s) ### How many days until April Fools' Day? - -# TODO: use date comparison to see if April Fool's has already gone for this year +today = date.today() # get today's date +afd = date(today.year, 4, 1) # get April Fool's for the same year +# use date comparison to see if April Fool's has already gone for this year # if it has, use the replace() function to get the date for next year +if afd < today: + print ("April Fool's day already went by %d days ago" % ((today-afd).days)) + afd = afd.replace(year=today.year + 1) # if so, get the date for next year - -# TODO: Now calculate the amount of time until April Fool's Day - +# Now calculate the amount of time until April Fool's Day +time_to_afd = afd - today +print ("It's just", time_to_afd.days, "days until next April Fools' Day!") diff --git a/Ch5 - Internet Data/htmlparsing_start.py b/Ch5 - Internet Data/htmlparsing_start.py index a759ac3..935fe46 100644 --- a/Ch5 - Internet Data/htmlparsing_start.py +++ b/Ch5 - Internet Data/htmlparsing_start.py @@ -5,15 +5,37 @@ from html.parser import HTMLParser +paragraphs = 0 + class MyHTMLParser(HTMLParser): def handle_comment(self, data): - pass + print("Encountered a comment:", data) + pos = self.getpos() + print("at line:",pos[0],"position", pos[1]) def handle_starttag(self, tag, attrs): - pass + print("Encountered a start tag:", tag) + pos = self.getpos() + print("at line:",pos[0],"position", pos[1]) + + global paragraphs + if tag == "p": + paragraphs += 1 + + if len(attrs) > 0: + print("Attributes:") + + for a in attrs: + print("\t", a[0], "=", a[1]) + def handle_data(self, data): - pass + if data.isspace(): + return + + print("Encountered text data:", data) + pos = self.getpos() + print("at line:",pos[0],"position", pos[1]) def main(): # instantiate the parser and feed it some HTML @@ -24,6 +46,7 @@ def main(): contents = f.read() # read the entire file parser.feed(contents) + print("Paragraph tags:", paragraphs) if __name__ == "__main__": main() \ No newline at end of file diff --git a/Ch5 - Internet Data/xmlparsing_start.py b/Ch5 - Internet Data/xmlparsing_start.py index 3129b0c..d1add20 100644 --- a/Ch5 - Internet Data/xmlparsing_start.py +++ b/Ch5 - Internet Data/xmlparsing_start.py @@ -3,20 +3,31 @@ # LinkedIn Learning Python course by Joe Marini # +import xml.dom.minidom def main(): # use the parse() function to load and parse an XML file - + doc = xml.dom.minidom.parse("samplexml.xml") # print out the document node and the name of the first child tag - + print(doc.nodeName[1::1]) + print(doc.firstChild.tagName) # get a list of XML tags from the document and print each one - + skills = doc.getElementsByTagName("skill") + print(skills.length, "skills are listed") + for skill in skills: + print(skill.getAttribute("name")) # create a new XML tag and add it into the document - + newSkill = doc.createElement("skill") + newSkill.setAttribute("name", "jQUery") + doc.firstChild.appendChild(newSkill) + skills = doc.getElementsByTagName("skill") + print(skills.length, "skills are listed") + for skill in skills: + print(skill.getAttribute("name")) if __name__ == "__main__": main() diff --git a/docs/Python - API.pdf b/docs/Python - API.pdf new file mode 100644 index 0000000..1a73d20 Binary files /dev/null and b/docs/Python - API.pdf differ diff --git a/docs/Python - Functions.pdf b/docs/Python - Functions.pdf new file mode 100644 index 0000000..bafc56b Binary files /dev/null and b/docs/Python - Functions.pdf differ diff --git a/docs/Python - Loops.pdf b/docs/Python - Loops.pdf new file mode 100644 index 0000000..dcbb5b4 Binary files /dev/null and b/docs/Python - Loops.pdf differ diff --git a/docs/Python - Numpy.pdf b/docs/Python - Numpy.pdf new file mode 100644 index 0000000..9381fc4 Binary files /dev/null and b/docs/Python - Numpy.pdf differ diff --git a/docs/Python - Object Classes.pdf b/docs/Python - Object Classes.pdf new file mode 100644 index 0000000..10341ae Binary files /dev/null and b/docs/Python - Object Classes.pdf differ diff --git a/docs/Python - Pandas Library.pdf b/docs/Python - Pandas Library.pdf new file mode 100644 index 0000000..40e3c4f Binary files /dev/null and b/docs/Python - Pandas Library.pdf differ diff --git a/docs/Python - Read File with Open.pdf b/docs/Python - Read File with Open.pdf new file mode 100644 index 0000000..ee13d5c Binary files /dev/null and b/docs/Python - Read File with Open.pdf differ diff --git a/src/FileOpen.py b/src/FileOpen.py new file mode 100644 index 0000000..0a8fbf5 --- /dev/null +++ b/src/FileOpen.py @@ -0,0 +1,6 @@ +# Open a file from directory +with open("../List and Tuples.txt", "r") as file: + file_contents = file.readlines() + +print(type(file_contents)) +print(file_contents) \ No newline at end of file diff --git a/src/HttpRequest.py b/src/HttpRequest.py new file mode 100644 index 0000000..b182dba --- /dev/null +++ b/src/HttpRequest.py @@ -0,0 +1,16 @@ +import requests + +url = 'https://www.httpbin.org/get?name=Joseph&id=123' +payload = { + "name":"Joseph", + "id":"123" + } + +response = requests.get(url, payload) + +response.url +response.body +response.request.body +response.status_code +response.text +response.content.json() \ No newline at end of file diff --git a/src/LoadFromJson.py b/src/LoadFromJson.py new file mode 100644 index 0000000..1a2f9fa --- /dev/null +++ b/src/LoadFromJson.py @@ -0,0 +1,10 @@ +import json + +# Opening JSON file +with open('sample.json', 'r') as openfile: + + # Reading from json file + json_object = json.load(openfile) + +print(json_object) +print(type(json_object)) \ No newline at end of file diff --git a/src/LoadXLSX.py b/src/LoadXLSX.py new file mode 100644 index 0000000..d558f9c --- /dev/null +++ b/src/LoadXLSX.py @@ -0,0 +1,20 @@ +import pandas as pd +import piplite +from pyodide.http import pyfetch +await piplite.install(['seaborn', 'lxml', 'openpyxl']) + +# Not needed unless you're running locally +# import urllib.request +# urllib.request.urlretrieve("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/file_example_XLSX_10.xlsx", "sample.xlsx") + +filename = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/file_example_XLSX_10.xlsx" + +async def download(url, filename): + response = await pyfetch(url) + if response.status == 200: + with open(filename, "wb") as f: + f.write(await response.bytes()) + +await download(filename, "file_example_XLSX_10.xlsx") + +df = pd.read_excel("file_example_XLSX_10.xlsx") \ No newline at end of file diff --git a/src/LoadXMLFile.py b/src/LoadXMLFile.py new file mode 100644 index 0000000..1989a2a --- /dev/null +++ b/src/LoadXMLFile.py @@ -0,0 +1,43 @@ +# Not needed unless running locally +# !wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/Sample-employee-XML-file.xml + +import xml.etree.ElementTree as etree +import pandas as pd + +filename = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/Sample-employee-XML-file.xml" + +async def download(url, filename): + response = await pyfetch(url) + if response.status == 200: + with open(filename, "wb") as f: + f.write(await response.bytes()) + +await download(filename, "Sample-employee-XML-file.xml") + + +tree = etree.parse("Sample-employee-XML-file.xml") + +root = tree.getroot() +columns = ["firstname", "lastname", "title", "division", "building","room"] + +datatframe = pd.DataFrame(columns = columns) + +for node in root: + + firstname = node.find("firstname").text + + lastname = node.find("lastname").text + + title = node.find("title").text + + division = node.find("division").text + + building = node.find("building").text + + room = node.find("room").text + + datatframe = pd.concat([datatframe, pd.Series([firstname, lastname, title, division, building, room], index = columns)], ignore_index = True) + + df=pd.read_xml("Sample-employee-XML-file.xml", xpath="/employees/details") + + datatframe.to_csv("employee.csv", index=False) \ No newline at end of file diff --git a/src/PlotVector.py b/src/PlotVector.py new file mode 100644 index 0000000..64f7905 --- /dev/null +++ b/src/PlotVector.py @@ -0,0 +1,16 @@ +import time +import sys +import numpy as np + +import matplotlib.pyplot as plt +%matplotlib inline + +def Plotvec2(a,b): + ax = plt.axes()# to generate the full window axes + ax.arrow(0, 0, *a, head_width=0.05, color ='r', head_length=0.1)#Add an arrow to the a Axes with arrow head width 0.05, color red and arrow head length 0.1 + plt.text(*(a + 0.1), 'a') + ax.arrow(0, 0, *b, head_width=0.05, color ='b', head_length=0.1)#Add an arrow to the b Axes with arrow head width 0.05, color blue and arrow head length 0.1 + plt.text(*(b + 0.1), 'b') + plt.ylim(-2, 2)#set the ylim to bottom(-2), top(2) + plt.xlim(-2, 2)#set the xlim to left(-2), right(2) + \ No newline at end of file diff --git a/src/TextAnalyzer.py b/src/TextAnalyzer.py new file mode 100644 index 0000000..47abe2a --- /dev/null +++ b/src/TextAnalyzer.py @@ -0,0 +1,49 @@ +class TextAnalyzer(object): + + rawText = "" + fmtText = "" + + def __init__ (self, text): + # assign raw text + self.rawText = text + + # remove punctuation + formattedText = text.replace('.','').replace('!','').replace('?','').replace(',','') + + # make text lowercase + formattedText = formattedText.lower() + + self.fmtText = formattedText + + def freqAll(self): + # split text into words + wordList = self.fmtText.split(' ') + + # Create dictionary + freqMap = {} + for word in set(wordList): # use set to remove duplicates in list + freqMap[word] = wordList.count(word) + + return freqMap + + def freqOf(self,word): + # get frequency map + freqDict = self.freqAll() + + if word in freqDict: + return freqDict[word] + else: + return 0 + +givenstring="Lorem ipsum dolor! diam amet, consetetur Lorem magna. sed diam nonumy eirmod tempor. diam et labore? et diam magna. et diam amet." + +analyzer = TextAnalyzer(givenstring) + +print("Raw Text: " + analyzer.rawText) +print("Formatted Text: " + analyzer.fmtText) + +freqMap = analyzer.freqAll() +print("Frequency All: ",freqMap) + +word = "lorem" +print("Frequency of ", word ,": " , analyzer.freqOf(word)) \ No newline at end of file diff --git a/src/WebScraping.py b/src/WebScraping.py new file mode 100644 index 0000000..15b0273 --- /dev/null +++ b/src/WebScraping.py @@ -0,0 +1,18 @@ +import requests +from bs4 import BeautifulSoup + +url='' +page = requests.get(url).text + +# Creates a Beautiful Soup object +soup = BeautifulSoup(page, 'html.parser') + +# Pulls all instances of tag +artists = soup.find_all('a') + +# Clears data from all tags +for artist in artists: + names = artist.contents[0] + fullLink = artist.get('href') + print(names) + print(fullLink) \ No newline at end of file diff --git a/src/WriteToJson.py b/src/WriteToJson.py new file mode 100644 index 0000000..29dde82 --- /dev/null +++ b/src/WriteToJson.py @@ -0,0 +1,27 @@ +import json + +person = { + 'first_name' : 'Mark', + 'last_name' : 'abc', + 'age' : 27, + 'address': { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021-3100" + } +} + +# writing JSON object using json.dump +with open('person.json', 'w') as f: + json.dump(person, f) + +# Serializing json +json_object = json.dumps(person, indent = 4) + +# Writing to sample.json +with open("sample.json", "w") as outfile: + outfile.write(json_object) + +print(person) +print(json_object) \ No newline at end of file diff --git a/src/WriteXMLFile.py b/src/WriteXMLFile.py new file mode 100644 index 0000000..08092ec --- /dev/null +++ b/src/WriteXMLFile.py @@ -0,0 +1,18 @@ +import xml.etree.ElementTree as ET + +# create the file structure +employee = ET.Element('employee') +details = ET.SubElement(employee, 'details') +first = ET.SubElement(details, 'firstname') +second = ET.SubElement(details, 'lastname') +third = ET.SubElement(details, 'age') +first.text = 'Shiv' +second.text = 'Mishra' +third.text = '23' + +# create a new XML file with the results +mydata1 = ET.ElementTree(employee) +# myfile = open("items2.xml", "wb") +# myfile.write(mydata) +with open("new_sample.xml", "wb") as files: + mydata1.write(files) \ No newline at end of file diff --git a/src/libraries.txt b/src/libraries.txt new file mode 100644 index 0000000..2f2672c --- /dev/null +++ b/src/libraries.txt @@ -0,0 +1,11 @@ +Pandas: https://pandas.pydata.org/ + +NumPy: https://numpy.org/ + +Random User: https://randomuser.me/documentation#intro + +FrutyVice: https://www.fruityvice.com/ + +Free public APIs: https://mixedanalytics.com/blog/list-actually-free-open-no-auth-needed-apis/ + +Beautiful Soup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/# \ No newline at end of file diff --git a/src/new_sample.xml b/src/new_sample.xml new file mode 100644 index 0000000..637629d --- /dev/null +++ b/src/new_sample.xml @@ -0,0 +1 @@ +
ShivMishra23
\ No newline at end of file diff --git a/src/sample.json b/src/sample.json new file mode 100644 index 0000000..4f0ad54 --- /dev/null +++ b/src/sample.json @@ -0,0 +1,11 @@ +{ + "first_name": "Mark", + "last_name": "abc", + "age": 27, + "address": { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021-3100" + } +} \ No newline at end of file