diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..be6be06 Binary files /dev/null and b/.DS_Store differ diff --git a/Ch2 - Basics/challenge_start.py b/Ch2 - Basics/challenge_start.py new file mode 100644 index 0000000..b42a281 --- /dev/null +++ b/Ch2 - Basics/challenge_start.py @@ -0,0 +1,20 @@ +# define a function +# convert string to lowercase +# reverse word and test if equal to original string +# need to remove punctuation and spaces +# need to work with numbers or convert number to string... str() + + +def main(): + string=input("Enter String to test for palindrome or 'exit':") + string = str(string).lower() + new_string = ''.join(char for char in string if char.isalnum()) + if new_string== 'exit': + return + elif new_string == new_string[::-1]: + print("Palindrome test:",True) + else: + print("Palindrome test:",False) + +if __name__ == "__main__": + main() diff --git a/Ch2 - Basics/classes_start.py b/Ch2 - Basics/classes_start.py index de3226d..387a841 100644 --- a/Ch2 - Basics/classes_start.py +++ b/Ch2 - Basics/classes_start.py @@ -3,3 +3,48 @@ # LinkedIn Learning Python course by Joe Marini # +class Vehicle(): + def __init__(self, bodystyle): + self.bodystyle = bodystyle + + def drive(self, speed): + self.mode = "driving" + self.speed = speed + + +class Car(Vehicle): + def __init__(self, enginetype): + super().__init__("Car") + self.wheels = 4 + self.doors = 4 + self.engine = enginetype + + def drive(self, speed): + super().drive(speed) + print("Driving my", self.engine, "car at ", self.speed) + +class Motorcycle(Vehicle): + def __init__(self, enginetype, sidecar): + super().__init__("Motorcycle") + if (sidecar): + self.wheels = 3 + else: + self.wheels = 2 + self.doors = 0 + self.engine = enginetype + + def drive(self, speed): + super().drive(speed) + print("Driving my", self.engine, "Car at ", self.speed) + +car1 = Car("gas") +car2 = Car("electric") +mc1 = Motorcycle("gas", True) + +print(mc1.wheels) +print(car1.engine) +print(car2.doors) + +car1.drive(30) +car2.drive(40) +mc1.drive(50) diff --git a/Ch2 - Basics/conditionals_start.py b/Ch2 - Basics/conditionals_start.py index f6b58d6..0c666c5 100644 --- a/Ch2 - Basics/conditionals_start.py +++ b/Ch2 - Basics/conditionals_start.py @@ -6,14 +6,33 @@ def main(): - x, y = 10, 100 + x, y = 1000, 100 # conditional flow uses if, elif, else + if x < y: + result = "x is less than y" + elif x == y: + result = " x is the same as y" + else: + result = " x is greater than y" + print(result) # conditional statements let you use "a if C else b" - + result = "x is less than y" if x < y else "x is greater or equal to y" + print(result) # match-case makes it easy to compare multiple values - value = "one" + value = "three" + match value: + case "one": + result = 1 + case "two": + result = 2 + case "three" | "four": + result = (3,4) + case _: + result = -1 + + print(result) if __name__ == "__main__": main() diff --git a/Ch2 - Basics/exceptions_start.py b/Ch2 - Basics/exceptions_start.py index a1209c4..8298077 100644 --- a/Ch2 - Basics/exceptions_start.py +++ b/Ch2 - Basics/exceptions_start.py @@ -2,13 +2,27 @@ # Example file for working with classes # LinkedIn Learning Python course by Joe Marini # +0 # Errors can happen in programs, and we need a clean way to handle them # TODO: This code will cause an error because you can't divide by zero: - -# TODO: Exceptions provide a way of catching errors and then handling them in +# x = 10 / 0 +# TODO: Exceptions provide a way of catching errors and then handling them in # a separate section of the code to group them together - +try: + x = 10 / 0 +except: + print("Well that didn't work!") # TODO: You can also catch specific exceptions - +try: + answer = input("What should I divide 10 by?") + num = int(answer) + print(10 / num) +except ZeroDivisionError as e: + print("You can't divide by zero!") +except ValueError as e: + print(e, "isn't a valid number!") + print(e) +finally: + print("The finally section always runs") diff --git a/Ch2 - Basics/functions_start.py b/Ch2 - Basics/functions_start.py index 56cb247..7a2a1b6 100644 --- a/Ch2 - Basics/functions_start.py +++ b/Ch2 - Basics/functions_start.py @@ -5,17 +5,45 @@ # TODO: define a basic function - +def func1(): + print("I am a function") # TODO: function that takes arguments - +def func2(arg1, arg2): + print(arg1, " ", arg2) # TODO: function that returns a value - +def cube(x): + return x * x * x # TODO: function with default value for an argument - +def power(num, x=1): + result = 1; + for i in range(x): + result = result * num + return result # TODO: function with variable number of arguments +def multi_add(*args): + result = 0 + for x in args: + result = result + x + return result + + + +func1() +print((func1())) +print(func1) + +func2(10, 20) +print(func2(10, 20)) +print(cube(3)) + +print(power(2)) +print(power(2,3)) +print(power(x=3, num=2)) +print(multi_add(4, 5, 10, 4)) +print(multi_add(4, 5, 10, 4, 10)) diff --git a/Ch2 - Basics/helloworld_start.py b/Ch2 - Basics/helloworld_start.py index 7d6b753..c88d0ed 100644 --- a/Ch2 - Basics/helloworld_start.py +++ b/Ch2 - Basics/helloworld_start.py @@ -3,4 +3,11 @@ # LinkedIn Learning Python course by Joe Marini # +def main(): + print('Hello World!') + name = input("What is your name?") + print("Nice to meet you!", name) + +if __name__ == "__main__": + main() diff --git a/Ch2 - Basics/loops_start.py b/Ch2 - Basics/loops_start.py index f7d2e75..a2b06a3 100644 --- a/Ch2 - Basics/loops_start.py +++ b/Ch2 - Basics/loops_start.py @@ -8,20 +8,35 @@ def main(): x = 0 # TODO: define a while loop + while (x < 5): + print(x) + x = x + 1 # TODO: define a for loop - + for x in range(15, 20): + print(x) # TODO: use a for loop over a collection days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] + for d in days: + print(d) + # TODO: use the break and continue statements + for x in range(5, 10): + # if x==7: + # break + if x % 2 == 0: + continue + print(x) + + + # TODO: using the enumerate() function to get index + for i,d in enumerate(days): + print(i, d) - # TODO: using the enumerate() function to get index - - if __name__ == "__main__": main() diff --git a/Ch2 - Basics/modules_start.py b/Ch2 - Basics/modules_start.py index 8c8bf6c..1497853 100644 --- a/Ch2 - Basics/modules_start.py +++ b/Ch2 - Basics/modules_start.py @@ -3,12 +3,13 @@ # TODO: import the math module, which contains features for working with mathematics +import math # TODO: the math module contains lots of pre-built functions +print("The square root of 16 is", math.sqrt(16)) - -# TODO: in addition to functions, some modules contain useful constants - +# TODO: in addition to functions, some modules contain useful constants +print("Pi is", math.pi) # TODO: try some of the math functions for yourself here: diff --git a/Ch2 - Basics/variables_start.py b/Ch2 - Basics/variables_start.py index b2756cc..7d37f44 100644 --- a/Ch2 - Basics/variables_start.py +++ b/Ch2 - Basics/variables_start.py @@ -1,4 +1,4 @@ -# +# # Example file for variables # LinkedIn Learning Python course by Joe Marini # @@ -22,16 +22,34 @@ print(mydict) # re-declaring a variable works +myint = "abc" +print(myint) # to access a member of a sequence type, use [] +print(mylist[2]) +print(mytuple[1]) + # use slices to get parts of a sequence +print(mylist[1:5]) +print(mylist[1:5:2]) # you can use slices to reverse a sequence - +print(mylist[::-1]) # dictionaries are accessed via keys +print(mydict["one"]) # ERROR: variables of different types cannot be combined - +# print("string type" + 123) // error! +print("string type" + str(123)) # Global vs. local variables in functions +def someFunction(): + global mystr + mystr = "def" + print(mystr) + +someFunction() +print(mystr) +del mystr +print(mystr) diff --git a/Ch3 - Files/archive.zip b/Ch3 - Files/archive.zip new file mode 100644 index 0000000..04050ce Binary files /dev/null and b/Ch3 - Files/archive.zip differ diff --git a/Ch3 - Files/challenge.py b/Ch3 - Files/challenge.py new file mode 100644 index 0000000..37e69a0 --- /dev/null +++ b/Ch3 - Files/challenge.py @@ -0,0 +1,33 @@ +# make a program to make a new directory with a txt file in it +# the txt file needs to have all the names of the files listed and the bytes of all of them +# define a function +# use listdir() to return a list containing the names of the entries in the directory given by path +# use mkdir() to create a directory for the new .txt file + +import os +from os import path + +def main(): + src = path.realpath("challenge.py") + root_dir, tail = path.split(src) + list = os.listdir(root_dir) + + os.mkdir("results") + myfile = open("./results/results.txt", "w+") + bytes = 0 + for x in list: + if os.path.isfile(x): + bytes += os.path.getsize(x) + myfile.write('Total bytecount: ' + str(bytes) + '\n') + myfile.write('Files list: \n') + myfile.write('---------------- \n') + + for x in list: + if os.path.isfile(x): + myfile.write(x + '\n') + + + myfile.close() + +if __name__ == "__main__": + main() diff --git a/Ch3 - Files/files_start.py b/Ch3 - Files/files_start.py index fb026bb..a960f2a 100644 --- a/Ch3 - Files/files_start.py +++ b/Ch3 - Files/files_start.py @@ -4,21 +4,29 @@ # -def main(): +def main(): # Open a file for writing and create it if it doesn't exist + # myfile = open("textfilez.txt", "w+") - # Open the file for appending text to the end - + # myfile = open("textfile.txt", "a+") # write some lines of data to the file + # for i in range(10): + # myfile.write("This is some new text\n") - # close the file when done + # myfile.close() + - # Open the file back up and read the contents + myfile = open("textfile.txt", "r") + if myfile.mode == 'r': + # contents = myfile.read() + # print(contents) + fl = myfile.readlines() + for x in fl: + print(x) - if __name__ == "__main__": main() diff --git a/Ch3 - Files/newfile.txt b/Ch3 - Files/newfile.txt new file mode 100644 index 0000000..0d5bc3a --- /dev/null +++ b/Ch3 - Files/newfile.txt @@ -0,0 +1,20 @@ +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text diff --git a/Ch3 - Files/ospathutils_start.py b/Ch3 - Files/ospathutils_start.py index 3384cbd..9844a90 100644 --- a/Ch3 - Files/ospathutils_start.py +++ b/Ch3 - Files/ospathutils_start.py @@ -12,19 +12,25 @@ def main(): # Print the name of the OS + print(os.name) - # Check for item existence and type + print("Item exists:", str(path.exists("textfile.txt"))) + print("Item is a file:", path.isfile("textfile.txt")) + print("Item is a directory:", path.isdir("textfile.txt")) - # Work with file paths + print("Item's path:", path.realpath("textfile.txt")) + print("Item's path and name:", path.split(path.realpath("textfile.txt"))) - # Get the modification time + t = time.ctime(path.getmtime("textfile.txt")) + print(t) + print(datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))) - # Calculate how long ago the item was modified - - + td = datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime("textfile.txt")) + print("It has been", td, "since the file was modified") + print("Or,", td.total_seconds(), "seconds") if __name__ == "__main__": main() diff --git a/Ch3 - Files/results/results.txt b/Ch3 - Files/results/results.txt new file mode 100644 index 0000000..c2fc35c --- /dev/null +++ b/Ch3 - Files/results/results.txt @@ -0,0 +1,16 @@ +Total bytecount:22881 +Files list: +-------------- +.DS_Store +ospathutils_finished.py +shell_start.py +testzip.zip +files_finished.py +textfile.txt.bak +newfile.txt +shell_finished.py +challenge_solution.py +archive.zip +files_start.py +challenge.py +ospathutils_start.py diff --git a/Ch3 - Files/shell_start.py b/Ch3 - Files/shell_start.py index 5cb9ec5..ff197bc 100644 --- a/Ch3 - Files/shell_start.py +++ b/Ch3 - Files/shell_start.py @@ -3,22 +3,33 @@ # LinkedIn Learning Python course by Joe Marini # +from distutils.archive_util import make_archive import os from os import path +import shutil +from shutil import make_archive +from zipfile import ZipFile def main(): # make a duplicate of an existing file - if path.exists("textfile.txt"): + if path.exists("textfile.txt.bak"): # get the path to the file in the current directory - + src = path.realpath("textfile.txt") + # dst = src + ".bak" + # shutil.copy(src, dst) # let's make a backup copy by appending "bak" to the name - + # rename the original file - - # now put things into a ZIP archive + # os.rename("textfile.txt", "newfile.txt") + # now put things into a ZIP archive + # root_dir, tail = path.split(src) + # shutil.make_archive("archive", "zip", root_dir) # more fine-grained control over ZIP files + with ZipFile("testzip.zip", "w") as newzip: + newzip.write("newfile.txt") + newzip.write("textfile.txt.bak") + - if __name__ == "__main__": main() diff --git a/Ch3 - Files/testzip.zip b/Ch3 - Files/testzip.zip new file mode 100644 index 0000000..dd90b5d Binary files /dev/null and b/Ch3 - Files/testzip.zip differ diff --git a/Ch3 - Files/textfile.txt.bak b/Ch3 - Files/textfile.txt.bak new file mode 100644 index 0000000..0d5bc3a --- /dev/null +++ b/Ch3 - Files/textfile.txt.bak @@ -0,0 +1,20 @@ +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text +This is some new text diff --git a/Ch4 - Dates and Times/calendars_start.py b/Ch4 - Dates and Times/calendars_start.py index 2963f70..7ec9381 100644 --- a/Ch4 - Dates and Times/calendars_start.py +++ b/Ch4 - Dates and Times/calendars_start.py @@ -5,24 +5,43 @@ # TODO: import the calendar module - +import calendar # TODO: create a plain text calendar - +c = calendar.TextCalendar(calendar.SUNDAY) +# str = c.formatmonth(2022, 1, 0, 0) +# print(str) # TODO: create an HTML formatted calendar - - +# hc = calendar.HTMLCalendar(calendar.SUNDAY) +# str = hc.formatmonth(2022, 1) +# print(str) # TODO: 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) - # TODO: 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) # TODO: 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): + cal = calendar.monthcalendar(2022, m) + weekone = cal[0] + weektwo = cal[1] + if weekone[calendar.FRIDAY] != 0: + meetday = weekone[calendar.FRIDAY] + else: + meetday = weektwo[calendar.FRIDAY] + + print(calendar.month_name[m], meetday) diff --git a/Ch4 - Dates and Times/challenge_start.py b/Ch4 - Dates and Times/challenge_start.py index 9da42cb..6928fe5 100644 --- a/Ch4 - Dates and Times/challenge_start.py +++ b/Ch4 - Dates and Times/challenge_start.py @@ -1,5 +1,51 @@ # Start file for programming challenge for Learning Python course # LinkedIn Learning Python course by Joe Marini -# +# print to the terminal, which day of the week do you want to count? +# then give a list of days with the indexes +# if they type exit, then quit the program +# if they type a valid number then ask them what month +# then what year +# when they type the year, there needs to be an equation to count the number of days in the month of that year + import calendar + +def main(): + + daysinmonth = 0 + dayoftheweek = 0 + month = 0 + year = 0 + + dayoftheweek = input("Which day of the week do you want to count? \n 0: Monday \n 1: Tuesday \n 2: Wednesday \n 3: Thursday \n 4: Friday \n 5: Saturday \n 6: Sunday \n or 'exit' to quit \n? " ) + if dayoftheweek == 'exit': + return + elif dayoftheweek.isnumeric() == False: + print("Value must be a positive integer!") + main() + + month = input("Enter Month: ") + if month == 'exit': + return + elif month.isnumeric() == False: + print("Value must be a positive integer!") + main() + + year = input("Enter Year: ") + if year == 'exit': + return + elif year.isnumeric() == False: + print("Value must be a positive integer!") + main() + + c = calendar.monthcalendar(int(year), int(month)) + for i in c: + if i[int(dayoftheweek)] != 0: + daysinmonth +=1 + + + + print('There are '+ str(daysinmonth) + ' days in the month of ' + str(month) +', ' + str(year)) + main() +if __name__ == "__main__": + main() diff --git a/Ch4 - Dates and Times/dates_start.py b/Ch4 - Dates and Times/dates_start.py index 9091c40..a8fb1dc 100644 --- a/Ch4 - Dates and Times/dates_start.py +++ b/Ch4 - Dates and Times/dates_start.py @@ -3,28 +3,37 @@ # 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) # 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) + print("Today's weekday number is", today.weekday()) + days = ["mon", "tues", "wed", "thurs", "fri", "sat", "sun"] + print("Which is a ", days[today.weekday()]) - ## DATETIME OBJECTS # TODO: Get today's date from the datetime class + today = datetime.now() + print ("The current date and time is ", today) - # TODO: Get the current time - + t = datetime.time(datetime.now()) + print(t) + + + - if __name__ == "__main__": main() - \ No newline at end of file diff --git a/Ch4 - Dates and Times/formatting_start.py b/Ch4 - Dates and Times/formatting_start.py index 6c40839..67f21df 100644 --- a/Ch4 - Dates and Times/formatting_start.py +++ b/Ch4 - Dates and Times/formatting_start.py @@ -8,21 +8,26 @@ def main(): # Times and dates can be formatted using a set of predefined string - # control codes + # control codes + + now = datetime.now() - #### Date Formatting #### - - # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month + # %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("Local date and time: %c")) + print(now.strftime("Local date and time: %c")) + print(now.strftime("Local 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")) + if __name__ == "__main__": main() diff --git a/Ch4 - Dates and Times/timedeltas_start.py b/Ch4 - Dates and Times/timedeltas_start.py index a6b62bc..d4ba51c 100644 --- a/Ch4 - Dates and Times/timedeltas_start.py +++ b/Ch4 - Dates and Times/timedeltas_start.py @@ -7,29 +7,35 @@ 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: " + str(now)) # TODO: print today's date one year from now - +print ("one year from now it will be: " + str(now + timedelta(days=365))) # TODO: create a timedelta that uses more than one argument - +print ("in four weeks and 3 days it will be: " + str(now + timedelta(weeks=4, days=3))) # TODO: calculate the date 1 week ago, formatted as a string ### How many days until April Fools' Day? - +today = date.today() +xmas = date(today.year, 12, 25) # TODO: 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 xmas < today: + print ("Christmas already went by %d days ago" % ((today-xmas).days)) + xmas = xmas.replace(year=today.year + 1) - -# TODO: Now calculate the amount of time until April Fool's Day - +# TODO: Now calculate the amount of time until April Fool's Day +time_to_xmas = xmas - today +print ("It's just", time_to_xmas.days, "days until Christmas!") diff --git a/Ch5 - Internet Data/htmlparsing_start.py b/Ch5 - Internet Data/htmlparsing_start.py index a759ac3..28a3837 100644 --- a/Ch5 - Internet Data/htmlparsing_start.py +++ b/Ch5 - Internet Data/htmlparsing_start.py @@ -1,29 +1,46 @@ -# +# # Example file for parsing and processing HTML # LinkedIn Learning Python course by Joe Marini # 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 + 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 parser = MyHTMLParser() - + f = open("samplehtml.html") if f.mode == "r": contents = f.read() # read the entire file - parser.feed(contents) + parser.feed(contents) + print(paragraphs) if __name__ == "__main__": main() - \ No newline at end of file diff --git a/Ch5 - Internet Data/inetdata_start.py b/Ch5 - Internet Data/inetdata_start.py index 86dc094..0a69095 100644 --- a/Ch5 - Internet Data/inetdata_start.py +++ b/Ch5 - Internet Data/inetdata_start.py @@ -1,10 +1,16 @@ -# +# # Example file for retrieving data from the internet # LinkedIn Learning Python course by Joe Marini # +import urllib.request + def main(): - pass # this is a placeholder, do-nothing statement + weburl = urllib.request.urlopen("http://www.google.com") + print("result code:", weburl.getcode()) + data = weburl.read() + print(data) + if __name__ == "__main__": main() diff --git a/Ch5 - Internet Data/jsondata_finished.py b/Ch5 - Internet Data/jsondata_finished.py index d244ebf..583bccb 100644 --- a/Ch5 - Internet Data/jsondata_finished.py +++ b/Ch5 - Internet Data/jsondata_finished.py @@ -6,6 +6,7 @@ import urllib.request # instead of urllib2 like in Python 2.7 import json +import ssl def printResults(data): @@ -45,6 +46,7 @@ def main(): # define a variable to hold the source URL # In this case we'll use the free data feed from the USGS # This feed lists all earthquakes for the last day larger than Mag 2.5 + ssl._create_default_https_context = ssl._create_unverified_context urlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" # Open the URL and read the data diff --git a/Ch5 - Internet Data/jsondata_start.py b/Ch5 - Internet Data/jsondata_start.py index e0da623..da440eb 100644 --- a/Ch5 - Internet Data/jsondata_start.py +++ b/Ch5 - Internet Data/jsondata_start.py @@ -1,39 +1,59 @@ -# +# # Example file for parsing and processing JSON # LinkedIn Learning Python course by Joe Marini # -import urllib.request +import urllib.request +import json +import ssl def printResults(data): # Use the json module to load the string data into a dictionary theJSON = json.loads(data) - - # now we can access the contents of the JSON like any other Python object - - # output the number of events, plus the magnitude and each event name + # # now we can access the contents of the JSON like any other Python object + if "title" in theJSON["metadata"]: + print(theJSON["metadata"]["title"]) - - # for each event, print the place where it occurred + # # output the number of events, plus the magnitude and each event name + count = theJSON["metadata"]["count"] + print(count, "events recorded") + # for each event, print the place where it occurred + for i in theJSON["features"]: + print(i["properties"]["place"]) + print("--------------\n") # print the events that only have a magnitude greater than 4 - + for i in theJSON["features"]: + if i["properties"]["mag"] >= 4: + print(i["properties"]["mag"], i["properties"]["title"]) # print only the events where at least 1 person reported feeling something + print("felt quakes: ") + for i in theJSON["features"]: + feltReports = i["properties"]["felt"] + if (feltReports != None): + if (feltReports > 0): + print(i["properties"]["mag"], i["properties"] + ["place"], " reported " + str(feltReports) + " times") + - def main(): # define a variable to hold the source URL # In this case we'll use the free data feed from the USGS # This feed lists all earthquakes for the last day larger than Mag 2.5 - urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" + ssl._create_default_https_context = ssl._create_unverified_context + urlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" # Open the URL and read the data webUrl = urllib.request.urlopen(urlData) - print ("result code: " + str(webUrl.getcode())) - + print ("result code: ", webUrl.getcode()) + if (webUrl.getcode() == 200): + data = webUrl.read() + printResults(data) + else: + print("Recieved an error from the server, cannot print results", webUrl.getcode()) if __name__ == "__main__": main() diff --git a/Ch5 - Internet Data/xmlparsing_start.py b/Ch5 - Internet Data/xmlparsing_start.py index 3129b0c..1960571 100644 --- a/Ch5 - Internet Data/xmlparsing_start.py +++ b/Ch5 - Internet Data/xmlparsing_start.py @@ -1,23 +1,33 @@ -# +# # Example file for parsing and processing XML # 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) + 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() -