diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 97f37e0..0000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,3 +0,0 @@ -# Codeowners for these exercise files: -# * (asterisk) deotes "all files and folders" -# Example: * @producer @instructor diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 20ff87d..0000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,34 +0,0 @@ - - -## Issue Overview - - -## Describe your environment - - -## Steps to Reproduce - -1. -2. -3. -4. - -## Expected Behavior - - -## Current Behavior - - -## Possible Solution - - -## Screenshots / Video - - -## Related Issues - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 6ae59ec..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index 1732566..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Copy To Branches -on: - workflow_dispatch: -jobs: - copy-to-branches: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Copy To Branches Action - uses: planetoftheweb/copy-to-branches@v1 diff --git a/Ch2 - Basics/challenge_palindromes.py b/Ch2 - Basics/challenge_palindromes.py new file mode 100644 index 0000000..480bb02 --- /dev/null +++ b/Ch2 - Basics/challenge_palindromes.py @@ -0,0 +1,19 @@ +import re +from unidecode import unidecode + + +def palindrome(test): + sanitized = re.sub(r'[^a-zA-Z0-9]+', "", unidecode(test.lower())) + return sanitized == sanitized[::-1] + + +def main(): + while (True): + test = input("Enter string to test for palindrome or 'exit': ") + if test == 'exit': + exit(0) + print("Palindrome test: {}".format(palindrome(test))) + + +if __name__ == "__main__": + main() diff --git a/Ch2 - Basics/challenge_solution.py b/Ch2 - Basics/challenge_solution.py deleted file mode 100644 index caeb9dc..0000000 --- a/Ch2 - Basics/challenge_solution.py +++ /dev/null @@ -1,40 +0,0 @@ -# Solution to programming challenge for Learning Python course -# LinkedIn Learning Python course by Joe Marini -# - -def is_palindrome(teststr): - # one way to do it: calculate the reverse of the string - # reversestr = "" - # strindx = len(teststr)-1 - # while (strindx >= 0): - # reversestr += teststr[strindx] - # strindx -= 1 - - # if teststr == reversestr: - # return True - # return False - - # more advanced: use the slice trick to reverse the string - if teststr == teststr[::-1]: - return True - return False - -run = True -while (run): - teststr = input("Enter string to test for palindrome or 'exit':") - - # If the user types "exit" then quit the program - if teststr == "exit": - run = False - break - - # convert the string to all lower case - teststr = teststr.lower() - - # strip all the spaces and punctuation from the string - newstr = "" - for x in teststr: - if x.isalnum(): - newstr += x - - print("Palindrome test:", is_palindrome(newstr)) diff --git a/Ch2 - Basics/classes_finished.py b/Ch2 - Basics/classes_finished.py deleted file mode 100644 index f8ad79d..0000000 --- a/Ch2 - Basics/classes_finished.py +++ /dev/null @@ -1,52 +0,0 @@ -# -# Example file for working with classes -# 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, hassidecar): - super().__init__("Motorcycle") - if (hassidecar): - self.wheels = 2 - else: - self.wheels = 3 - self.doors = 0 - self.engine = enginetype - - def drive(self, speed): - super().drive(speed) - print("Driving my", self.engine, "motorcylce 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/classes_start.py b/Ch2 - Basics/classes_start.py index de3226d..44c599a 100644 --- a/Ch2 - Basics/classes_start.py +++ b/Ch2 - Basics/classes_start.py @@ -1,5 +1,57 @@ -# -# Example file for working with classes -# 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 + + def park(self): + if self.mode == "driving": + self.mode = "parking" + self.speed = 0 + print("Parked my", self.bodystyle) + else: + print(self.bodystyle, "is already parked") + + +class Car(Vehicle): + def __init__(self, enginetype): + super().__init__("Car") + self.wheels = 4 + self.doors = 4 + self.enginetype = enginetype + + def drive(self, speed): + super().drive(speed) + print("Driving my", self.enginetype, "car at", speed) + + +class Motorcycle(Vehicle): + def __init__(self, enginetype, hassidecar): + super().__init__("Motorcycle") + if (hassidecar): + self.wheels = 3 + else: + self.wheels = 2 + self.doors = 0 + self.enginetype = enginetype + + +car1 = Car("gas") +car2 = Car("electric") +mc1 = Motorcycle("gas", True) + +print(mc1.wheels) +print(car1.enginetype) +print(car2.doors) + +car1.drive(30) +car2.drive(40) +mc1.drive(50) + +car1.park() +car2.park() +car1.park() +mc1.park() +mc1.park() diff --git a/Ch2 - Basics/conditionals_finished.py b/Ch2 - Basics/conditionals_finished.py deleted file mode 100644 index 2a77f66..0000000 --- a/Ch2 - Basics/conditionals_finished.py +++ /dev/null @@ -1,39 +0,0 @@ -# -# Example file for working with conditional statements -# LinkedIn Learning Python course by Joe Marini -# - - - -def main(): - x, y = 10, 100 - - # conditional flow uses if, elif, else - if x < y: - result = "x is less than y" - elif x == y: - result = "x is 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 than or equal to y" - print(result) - - # new in Python 3.10 - # the match-case construct can be used for multiple comparisons - value = "one" - 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/conditionals_start.py b/Ch2 - Basics/conditionals_start.py index f6b58d6..8521a45 100644 --- a/Ch2 - Basics/conditionals_start.py +++ b/Ch2 - Basics/conditionals_start.py @@ -1,19 +1,32 @@ -# -# Example file for working with conditional statements -# LinkedIn Learning Python course by Joe Marini -# - - - def main(): x, y = 10, 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" + 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_finished.py b/Ch2 - Basics/exceptions_finished.py deleted file mode 100644 index 4f09f1b..0000000 --- a/Ch2 - Basics/exceptions_finished.py +++ /dev/null @@ -1,29 +0,0 @@ -# -# Example file for working with classes -# LinkedIn Learning Python course by Joe Marini -# - -# Errors can happen in programs, and we need a clean way to handle them -# This code will cause an error because you can't divide by zero: -# x = 10 / 0 - -# 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!") - -# 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("You didn't give me a valid number!") - print(e) -finally: - print("The finally section always runs") - diff --git a/Ch2 - Basics/exceptions_start.py b/Ch2 - Basics/exceptions_start.py index a1209c4..bc580d0 100644 --- a/Ch2 - Basics/exceptions_start.py +++ b/Ch2 - Basics/exceptions_start.py @@ -1,14 +1,30 @@ -# -# Example file for working with classes -# LinkedIn Learning Python course by Joe Marini -# - # 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: +# x = 10 / 0 -# TODO: Exceptions provide a way of catching errors and then handling them in +# 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: + x = "10" / 0 +except ZeroDivisionError: + print("Can't divide by zero now, can we?") +except TypeError: + print("Well, that didn't work!") +try: + answer = input("What should I divide 10 by? ") + num = int(answer) + print(10 / num) +except ZeroDivisionError: + print("Can't divide by zero now, can we?") +except ValueError as error: + print("Well, '{}' isn't a number now, is it?".format(answer)) + print(error) +finally: + print("This always runs") diff --git a/Ch2 - Basics/functions_finished.py b/Ch2 - Basics/functions_finished.py deleted file mode 100644 index 19acda7..0000000 --- a/Ch2 - Basics/functions_finished.py +++ /dev/null @@ -1,43 +0,0 @@ -# -# Example file for working with functions -# LinkedIn Learning Python course by Joe Marini -# - - -# define a basic function -def func1(): - print("I am a function") - -# function that takes arguments -def func2(arg1, arg2): - print(arg1, " ", arg2) - -# function that returns a value -def cube(x): - return x*x*x - -# function with default value for an argument -def power(num, x=1): - result = 1 - for i in range(x): - result = result * num - return result - -# 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)) diff --git a/Ch2 - Basics/functions_start.py b/Ch2 - Basics/functions_start.py index 56cb247..fcded65 100644 --- a/Ch2 - Basics/functions_start.py +++ b/Ch2 - Basics/functions_start.py @@ -1,21 +1,45 @@ -# -# Example file for working with functions -# LinkedIn Learning Python course by Joe Marini -# - - # TODO: define a basic function +def func1(): + print("I'm 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_finished.py b/Ch2 - Basics/helloworld_finished.py deleted file mode 100644 index 8ff61a8..0000000 --- a/Ch2 - Basics/helloworld_finished.py +++ /dev/null @@ -1,13 +0,0 @@ -# -# Example file for HelloWorld -# 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/helloworld_start.py b/Ch2 - Basics/helloworld_start.py index 7d6b753..9b6ebbe 100644 --- a/Ch2 - Basics/helloworld_start.py +++ b/Ch2 - Basics/helloworld_start.py @@ -1,6 +1,8 @@ -# -# Example file for HelloWorld -# 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_finished.py b/Ch2 - Basics/loops_finished.py deleted file mode 100644 index b348924..0000000 --- a/Ch2 - Basics/loops_finished.py +++ /dev/null @@ -1,36 +0,0 @@ -# -# Example file for working with loops -# LinkedIn Learning Python course by Joe Marini -# - - -def main(): - x = 0 - - # define a while loop - while (x < 5): - print(x) - x = x + 1 - - # define a for loop - for x in range(5,10): - print (x) - - # use a for loop over a collection - days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] - for d in days: - print (d) - - # use the break and continue statements - for x in range(5,10): - #if (x == 7): break - #if (x % 2 == 0): continue - print (x) - - # using the enumerate() function to get index - days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] - for i, d in enumerate(days): - print (i, d) - -if __name__ == "__main__": - main() diff --git a/Ch2 - Basics/loops_start.py b/Ch2 - Basics/loops_start.py index f7d2e75..d4e758c 100644 --- a/Ch2 - Basics/loops_start.py +++ b/Ch2 - Basics/loops_start.py @@ -1,27 +1,36 @@ -# -# Example file for working with loops -# LinkedIn Learning Python course by Joe Marini -# - - def main(): x = 0 # TODO: define a while loop - + while (x < 5): + print(x) + x += 1 # TODO: define a for loop - + for x in range(5, 10): + print(x) # TODO: use a for loop over a collection - days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] - + days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + for day in days: + print(day) # TODO: use the break and continue statements + for x in range(5, 10): + if x == 7: + break + print(x) + + for x in range(5, 10): + if x == 7: + continue + print(x) + + # TODO: using the enumerate() function to get index + days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + for i, day in enumerate(days): + print(i, day) - # TODO: using the enumerate() function to get index - - if __name__ == "__main__": main() diff --git a/Ch2 - Basics/modules_finished.py b/Ch2 - Basics/modules_finished.py deleted file mode 100644 index 201462d..0000000 --- a/Ch2 - Basics/modules_finished.py +++ /dev/null @@ -1,13 +0,0 @@ -# LinkedIn Learning Python course by Joe Marini -# - -# import the math module, which contains features for working with mathematics -import math - -# the math module contains lots of pre-built functions -print("The square root of 16 is", math.sqrt(16)) - -# in addition to functions, some modules contain useful constants -print("Pi is:", math.pi) - -# try some of the math functions for yourself here: diff --git a/Ch2 - Basics/modules_start.py b/Ch2 - Basics/modules_start.py index 8c8bf6c..7a620a7 100644 --- a/Ch2 - Basics/modules_start.py +++ b/Ch2 - Basics/modules_start.py @@ -1,14 +1,53 @@ -# LinkedIn Learning Python course by Joe Marini -# - - # TODO: import the math module, which contains features for working with mathematics - +import math # TODO: the math module contains lots of pre-built functions +# value = int(input("Type an integer to get the square root: ")) +value = int("16") +print("The square root of {} is {}".format(value, math.sqrt(value))) - -# TODO: in addition to functions, some modules contain useful constants - +# TODO: in addition to functions, some modules contain useful constants +print("Pi is {}".format(math.pi)) # TODO: try some of the math functions for yourself here: +x = -96 +print("Return the absolute value of x ({}): {}".format(x, math.fabs(x))) + +x = 5 +print("Return n factorial as an integer ({}): {}".format(x, math.factorial(x))) + +x = 5 +print( + "Return True if x is neither an infinity nor a NaN, and False otherwise ({}): {}" + .format(x, math.isfinite(x)) +) + +x = math.nan +print( + "Return True if x is neither an infinity nor a NaN, and False otherwise ({}): {}" + .format(x, math.isfinite(x)) +) + +x = float('inf') +print( + "Return True if x is neither an infinity nor a NaN, and False otherwise ({}): {}" + .format(x, math.isfinite(x)) +) + +x = 5 +print( + "Return True if x is a positive or negative infinity, and False otherwise ({}): {}" + .format(x, math.isinf(x)) +) + +x = math.nan +print( + "Return True if x is a positive or negative infinity, and False otherwise ({}): {}" + .format(x, math.isinf(x)) +) + +x = float('inf') +print( + "Return True if x is a positive or negative infinity, and False otherwise ({}): {}" + .format(x, math.isinf(x)) +) diff --git a/Ch2 - Basics/variables_finished.py b/Ch2 - Basics/variables_finished.py deleted file mode 100644 index 4fc819e..0000000 --- a/Ch2 - Basics/variables_finished.py +++ /dev/null @@ -1,53 +0,0 @@ -# -# Example file for variables -# LinkedIn Learning Python course by Joe Marini -# - - -# Basic data types in Python: Numbers, Strings, Booleans, Sequences, Dictionaries -myint = 5 -myfloat = 13.2 -mystr = "This is a string" -mybool = True -mylist = [0, 1, "two", 3.2, False] -mytuple = (0, 1, 2) -mydict = {"one" : 1, "two" : 2} - -print(myint) -print(myfloat) -print(mystr) -print(mybool) -print(mylist) -print(mytuple) -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:4: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) -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/Ch2 - Basics/variables_start.py b/Ch2 - Basics/variables_start.py index b2756cc..b79a967 100644 --- a/Ch2 - Basics/variables_start.py +++ b/Ch2 - Basics/variables_start.py @@ -1,9 +1,3 @@ -# -# Example file for variables -# LinkedIn Learning Python course by Joe Marini -# - - # Basic data types in Python: Numbers, Strings, Booleans, Sequences, Dictionaries myint = 5 myfloat = 13.2 @@ -11,7 +5,7 @@ mybool = True mylist = [0, 1, "two", 3.2, False] mytuple = (0, 1, 2) -mydict = {"one" : 1, "two" : 2} +mydict = {"one": 1, "two": 2} print(myint) print(myfloat) @@ -22,16 +16,37 @@ 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) +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) # error diff --git a/Ch3 - Files/challenge_files.py b/Ch3 - Files/challenge_files.py new file mode 100644 index 0000000..75b46ed --- /dev/null +++ b/Ch3 - Files/challenge_files.py @@ -0,0 +1,46 @@ +# Create directory results +# Create file results.txt within directory +# Write into the created file +# total byte count of all files +# the listing of files from current directory + +from os import listdir, mkdir, path + + +def main(): + createDirectory("results") + writeData(computeData("./"), "results/results.txt") + + +def createDirectory(name): + try: + mkdir(name) + except FileExistsError: + print("Folder '{}' already exists".format(name)) + except Exception as e: + print("Could not create directory: {}".format(e)) + exit(1) + + +def writeData(data, filePath): + with open(filePath, "w+") as results: + if results.mode == "w+": + results.write("Total bytecount: {}\n".format(data[0])) + results.write("Files list:\n") + results.write("--------------\n") + results.write("{}\n".format("\n".join(data[1]))) + results.close() + + +def computeData(dir): + bytecount = 0 + files = [] + for item in listdir(dir): + if path.isfile(item): + bytecount += path.getsize(item) + files.append(item) + return bytecount, files + + +if __name__ == "__main__": + main() diff --git a/Ch3 - Files/challenge_solution.py b/Ch3 - Files/challenge_solution.py deleted file mode 100644 index 73c6c3d..0000000 --- a/Ch3 - Files/challenge_solution.py +++ /dev/null @@ -1,34 +0,0 @@ -# Solution to programming challenge for Learning Python course -# LinkedIn Learning Python course by Joe Marini -# - -import os - -totalbytes = 0 - -# get a list of all the files in the current directory -dirlist = os.listdir() -for entry in dirlist: - # make sure it's a file! - if os.path.isfile(entry): - # add the file size to the total - filesize = os.path.getsize(entry) - totalbytes += filesize - -# create a subdirectory called "results" -os.mkdir("results") - -# create the output file -resultsfile = open("results/results.txt", "w+") -if resultsfile.mode == "w+": - resultsfile.write("Total bytecount:" + str(totalbytes) + "\n") - resultsfile.write("Files list:\n") - resultsfile.write("--------------\n") - # write the results into the file - for entry in dirlist: - if os.path.isfile(entry): - # write the file name to the results ledger - resultsfile.write(entry + "\n") - - # close the file when done - resultsfile.close() diff --git a/Ch3 - Files/files_finished.py b/Ch3 - Files/files_finished.py deleted file mode 100644 index a88083a..0000000 --- a/Ch3 - Files/files_finished.py +++ /dev/null @@ -1,33 +0,0 @@ -# -# Read and write files using the built-in Python file methods -# LinkedIn Learning Python course by Joe Marini -# - - -def main(): - # Open a file for writing and create it if it doesn't exist - f = open("textfile.txt","w+") - - # Open the file for appending text to the end - # f = open("textfile.txt","a+") - - # write some lines of data to the file - for i in range(10): - f.write("This is line %d\r\n" % (i+1)) - - # close the file when done - f.close() - - # Open the file back up and read the contents - f = open("textfile.txt","r") - if f.mode == 'r': # check to make sure that the file was opened - # use the read() function to read the entire file - # contents = f.read() - # print (contents) - - fl = f.readlines() # readlines reads the individual lines into a list - for x in fl: - print (x) - -if __name__ == "__main__": - main() diff --git a/Ch3 - Files/files_start.py b/Ch3 - Files/files_start.py index fb026bb..5e72096 100644 --- a/Ch3 - Files/files_start.py +++ b/Ch3 - Files/files_start.py @@ -1,24 +1,27 @@ -# -# Read and write files using the built-in Python file methods -# LinkedIn Learning Python course by Joe Marini -# - - -def main(): +def main(): # Open a file for writing and create it if it doesn't exist + # myfile = open("textfile.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) + if myfile.mode == 'r': + lines = myfile.readlines() + for line in lines: + print(line) + - 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_finished.py b/Ch3 - Files/ospathutils_finished.py deleted file mode 100644 index e6b8fe4..0000000 --- a/Ch3 - Files/ospathutils_finished.py +++ /dev/null @@ -1,37 +0,0 @@ -# -# Example file for working with os.path module -# LinkedIn Learning Python course by Joe Marini -# - - -import os -from os import path -import datetime -from datetime import date, time, timedelta -import time - -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: " + str(path.isfile("textfile.txt"))) - print ("Item is a directory: " + str(path.isdir("textfile.txt"))) - - # Work with file paths - print ("Item's path: " + str(path.realpath("textfile.txt"))) - print ("Item's path and name: " + str(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 " + str(td) + " since the file was modified") - print ("Or, " + str(td.total_seconds()) + " seconds") - -if __name__ == "__main__": - main() diff --git a/Ch3 - Files/ospathutils_start.py b/Ch3 - Files/ospathutils_start.py index 3384cbd..92ca5b7 100644 --- a/Ch3 - Files/ospathutils_start.py +++ b/Ch3 - Files/ospathutils_start.py @@ -1,30 +1,33 @@ -# -# Example file for working with os.path module -# LinkedIn Learning Python course by Joe Marini -# - -import os -from os import path -import datetime -from datetime import date, time, timedelta +from os import name, path +from datetime import datetime import time def main(): # Print the name of the OS + print(name) - # Check for item existence and type + print("Item exists: {}".format(path.exists("textfile.txt"))) + print("Item is a file: {}".format(path.isfile("textfile.txt"))) + print("Item is a directory: {}".format(path.isdir("textfile.txt"))) - # Work with file paths + print("Item's path is: {}".format(path.realpath("textfile.txt"))) + print("Item's path and name: {}".format( + path.split(path.realpath("textfile.txt")) + )) - # Get the modification time + t = time.ctime(path.getmtime("textfile.txt")) + print(t) + print(datetime.fromtimestamp(path.getmtime("textfile.txt"))) - # Calculate how long ago the item was modified + td = datetime.now() - datetime.fromtimestamp(path.getmtime("textfile.txt")) + print("It has been {} since the file was modified".format(td)) + print("Or, {} seconds".format(td.total_seconds())) + - if __name__ == "__main__": main() diff --git a/Ch3 - Files/shell_finished.py b/Ch3 - Files/shell_finished.py deleted file mode 100644 index 63de251..0000000 --- a/Ch3 - Files/shell_finished.py +++ /dev/null @@ -1,36 +0,0 @@ -# -# Example file for working with filesystem shell methods -# LinkedIn Learning Python course by Joe Marini -# - -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"): - # get the path to the file in the current directory - src = path.realpath("textfile.txt"); - - # let's make a backup copy by appending "bak" to the name - dst = src + ".bak" - # now use the shell to make a copy of the file - shutil.copy(src,dst) - - # rename the original file - 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/shell_start.py b/Ch3 - Files/shell_start.py index 5cb9ec5..ecf39b9 100644 --- a/Ch3 - Files/shell_start.py +++ b/Ch3 - Files/shell_start.py @@ -1,24 +1,32 @@ -# -# Example file for working with filesystem shell methods -# LinkedIn Learning Python course by Joe Marini -# - import os +import shutil from os import path +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.bak") + # let's make a backup copy by appending "bak" to the name - + # dst = src + ".bak" + # shutil.copy(src, dst) + # rename the original file - + # os.rename(src, "newfile.txt") + # now put things into a ZIP archive + # root_dir, _ = path.split(src) + # make_archive("archive", "zip", root_dir) # more fine-grained control over ZIP files + with ZipFile("test_zip.zip", "w") as newzip: + newzip.write("newfile.txt") + newzip.write("textfile.txt.bak") + - if __name__ == "__main__": main() diff --git a/Ch3 - Files/textfile.txt b/Ch3 - Files/textfile.txt new file mode 100644 index 0000000..0d5bc3a --- /dev/null +++ b/Ch3 - Files/textfile.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/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_finished.py b/Ch4 - Dates and Times/calendars_finished.py deleted file mode 100644 index 1372384..0000000 --- a/Ch4 - Dates and Times/calendars_finished.py +++ /dev/null @@ -1,50 +0,0 @@ -# -# Example file for working with Calendars -# LinkedIn Learning Python course by Joe Marini -# - - -import calendar - -# create a plain text calendar -c = calendar.TextCalendar(calendar.SUNDAY) -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) - -# 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) - -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] - - 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)) diff --git a/Ch4 - Dates and Times/calendars_start.py b/Ch4 - Dates and Times/calendars_start.py index 2963f70..fbbb72c 100644 --- a/Ch4 - Dates and Times/calendars_start.py +++ b/Ch4 - Dates and Times/calendars_start.py @@ -1,28 +1,37 @@ -# -# Example file for working with Calendars -# LinkedIn Learning Python course by Joe Marini -# - - # TODO: import the calendar module - +import calendar # TODO: create a plain text calendar - +txtCal = calendar.TextCalendar(calendar.MONDAY) +print(txtCal.formatmonth(2023, 4)) # TODO: create an HTML formatted calendar - +htmlCal = calendar.HTMLCalendar(calendar.SUNDAY) +print(htmlCal.formatmonth(2023, 4)) # TODO: loop over the days of a month # zeroes mean that the day of the week is in an overlapping month +for day in txtCal.itermonthdays(2023, 4): + print(day) - # 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 month in range(1, 13): + cal = calendar.monthcalendar(2023, month) + weekone, weektwo = cal[0], cal[1] + if weekone[calendar.FRIDAY] != 0: + meetday = weekone[calendar.FRIDAY] + else: + meetday = weektwo[calendar.FRIDAY] + print(calendar.month_name[month], meetday) diff --git a/Ch4 - Dates and Times/challenge_dates_times.py b/Ch4 - Dates and Times/challenge_dates_times.py new file mode 100644 index 0000000..b4eccd6 --- /dev/null +++ b/Ch4 - Dates and Times/challenge_dates_times.py @@ -0,0 +1,76 @@ +import calendar + + +def main(): + while (True): + weekday = validWeekday() + year = validYear() + month = validMonth() + countOcurrences(weekday, year, month) + + +def validWeekday(): + while (True): + print("Which day of the week do you want to count?") + for i, day in enumerate(calendar.day_name): + print("{}: {}".format(i, day)) + print("Or 'exit' to quit") + userInput = input("? ") + if userInput == 'exit': + exit(0) + try: + weekday = int(userInput) + if weekday < 0 or weekday > 6: + raise ValueError() + return weekday + except: + print("Invalid value for the week: {}\n".format(userInput)) + continue + + +def validYear(): + while (True): + userInput = input("Enter year or 'exit' to quit: ") + if userInput == 'exit': + exit(0) + try: + year = int(userInput) + if year < 0: + raise ValueError() + return year + except: + print("Invalid value for the year: {}\n".format(userInput)) + continue + + +def validMonth(): + while (True): + userInput = input("Enter month or 'exit' to quit: ") + if userInput == 'exit': + exit(0) + try: + month = int(userInput) + if month < 1 or month > 12: + raise ValueError() + return month + except: + print("Invalid value for the month: {}\n".format(userInput)) + continue + + +def countOcurrences(weekday, year, month): + count = 0 + cal = calendar.monthcalendar(year, month) + for week in cal: + count += 1 if week[weekday] else 0 + print("There are {} {}s in {} of {}".format( + count, + list(calendar.day_name)[weekday], + list(calendar.month_name)[month], + year + )) + print("-----------\n") + + +if __name__ == "__main__": + main() diff --git a/Ch4 - Dates and Times/challenge_solution.py b/Ch4 - Dates and Times/challenge_solution.py deleted file mode 100644 index 7e57b30..0000000 --- a/Ch4 - Dates and Times/challenge_solution.py +++ /dev/null @@ -1,51 +0,0 @@ -# Solution to programming challenge for Learning Python course -# LinkedIn Learning Python course by Joe Marini -# - -import calendar - -# This function counts the number of the given weekday for the -# specified year and month and returns the result -def countdays(theyear, themonth, whichday): - daycount = 0 - weekslist = calendar.monthcalendar(theyear, themonth) - for week in weekslist: - if week[whichday] != 0: - daycount += 1 - return daycount - - -print("--Day counter program--\n") - -run = True -while(run): - try: - print("Which day of the week do you want to count?") - print("0: Monday") - print("1: Tuesday") - print("2: Wednesday") - print("3: Thursday") - print("4: Friday") - print("5: Saturday") - print("6: Sunday") - print("Or 'exit' to quit") - - theday = input("? ") - if theday == "exit": - run = False - break - day = int(theday) - - yearstr = input("Enter year: ") - year = int(yearstr) - - monthstr = input("Enter month: ") - month = int(monthstr) - - result = countdays(year, month, day) - print("There are " + str(result) + " of those days in the month and year specified") - print("-----------\n") - except Exception as e: - print(e) - print("Sorry, that's not valid input") - diff --git a/Ch4 - Dates and Times/challenge_start.py b/Ch4 - Dates and Times/challenge_start.py deleted file mode 100644 index 9da42cb..0000000 --- a/Ch4 - Dates and Times/challenge_start.py +++ /dev/null @@ -1,5 +0,0 @@ -# Start file for programming challenge for Learning Python course -# LinkedIn Learning Python course by Joe Marini -# - -import calendar diff --git a/Ch4 - Dates and Times/dates_finished.py b/Ch4 - Dates and Times/dates_finished.py deleted file mode 100644 index d67e5e9..0000000 --- a/Ch4 - Dates and Times/dates_finished.py +++ /dev/null @@ -1,37 +0,0 @@ -# -# Example file for working with date information -# LinkedIn Learning Python course by Joe Marini -# - - -from datetime import date -from datetime import time -from datetime import datetime - -def main(): - ## DATE OBJECTS - # Get today's date from the simple today() method from the date class - today = date.today() - print ("Today's date is ", today) - - # print out the date's individual components - print ("Date Components: ", today.day, today.month, today.year) - - # retrieve today's weekday (0=Monday, 6=Sunday) - print ("Today's Weekday #: ", today.weekday()) - days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] - print ("Which is a " + days[today.weekday()]) - - ## DATETIME OBJECTS - # Get today's date from the datetime class - today = datetime.now() - print ("The current date and time is ", today) - - # Get the current time - t = datetime.time(datetime.now()) - print ("The current time is ", t) - - -if __name__ == "__main__": - main() - \ 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..e152df4 100644 --- a/Ch4 - Dates and Times/dates_start.py +++ b/Ch4 - Dates and Times/dates_start.py @@ -1,30 +1,30 @@ -# -# Example file for working with date information -# LinkedIn Learning Python course by Joe Marini -# - +from datetime import date, datetime def main(): - ## DATE OBJECTS + # DATE OBJECTS # TODO: Get today's date from the simple today() method from the date class - + today = date.today() + print("Today is {}".format(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 # is {}".format(today.weekday())) + days = ["monday", "tuesday", "wednesday", + "thursday", "friday", "saturday", "sunday"] + print("Which is a {}".format(days[today.weekday()])) - - ## DATETIME OBJECTS + # DATETIME OBJECTS # TODO: Get today's date from the datetime class + today = datetime.now() + print("The current date and time is {}".format(today)) - # TODO: Get the current time + t = datetime.time(datetime.now()) + print("The current time is {}".format(t)) - - if __name__ == "__main__": main() - \ No newline at end of file diff --git a/Ch4 - Dates and Times/formatting_finished.py b/Ch4 - Dates and Times/formatting_finished.py deleted file mode 100644 index a8449d6..0000000 --- a/Ch4 - Dates and Times/formatting_finished.py +++ /dev/null @@ -1,33 +0,0 @@ -# -# Example file for formatting time and date output -# LinkedIn Learning Python course by Joe Marini -# - - -from datetime import datetime - -def main(): - # Times and dates can be formatted using a set of predefined string - # control codes - now = datetime.now() # get the current date and time - - #### Date Formatting #### - - # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month - print (now.strftime("The current year is: %Y")) # full year with century - print (now.strftime("%a, %d %B, %y")) # abbreviated day, num, full month, abbreviated year - - # %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/formatting_start.py b/Ch4 - Dates and Times/formatting_start.py index 6c40839..5afef05 100644 --- a/Ch4 - Dates and Times/formatting_start.py +++ b/Ch4 - Dates and Times/formatting_start.py @@ -1,28 +1,26 @@ -# -# Example file for formatting time and date output -# LinkedIn Learning Python course by Joe Marini -# - - from datetime import datetime + 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 - + 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 date %X")) #### Time Formatting #### - # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM - + print(now.strftime("Current time is %I:%M:%S %p")) + print(now.strftime("Current time is %H:%M:%S")) + if __name__ == "__main__": main() diff --git a/Ch4 - Dates and Times/timedeltas_finished.py b/Ch4 - Dates and Times/timedeltas_finished.py deleted file mode 100644 index 32588ed..0000000 --- a/Ch4 - Dates and Times/timedeltas_finished.py +++ /dev/null @@ -1,43 +0,0 @@ -# -# Example file for working with timedelta objects -# LinkedIn Learning Python course by Joe Marini -# - - -from datetime import date -from datetime import time -from datetime import datetime -from datetime import timedelta - -# construct a basic timedelta and print it -print (timedelta(days=365, hours=5, minutes=1)) - -# print today's date -now = datetime.now() -print ("today is: " + str(now)) - -# print today's date one year from now -print ("one year from now it will be: " + str(now + timedelta(days=365))) - -# 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? - -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 - -# 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/Ch4 - Dates and Times/timedeltas_start.py b/Ch4 - Dates and Times/timedeltas_start.py index a6b62bc..28da2b9 100644 --- a/Ch4 - Dates and Times/timedeltas_start.py +++ b/Ch4 - Dates and Times/timedeltas_start.py @@ -1,35 +1,38 @@ -# -# Example file for working with timedelta objects -# LinkedIn Learning Python course by Joe Marini -# - - -from datetime import date -from datetime import time -from datetime import datetime +from datetime import date, time, datetime, 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 {}".format(now)) # TODO: print today's date one year from now - +print("One year from now will be {}".format(now + timedelta(days=365))) # TODO: create a timedelta that uses more than one argument - +print("In two weeks and 3 days will be {}".format( + now + timedelta(weeks=2, days=3) +)) # TODO: calculate the date 1 week ago, formatted as a string +t = datetime.now() - timedelta(weeks=1) +print(t.strftime("One week ago it was %A %B %d, %Y")) - -### How many days until April Fools' Day? - +# How many days until April Fools' Day? +today = date.today() +aprilFoolsDay = date(today.year, 4, 1) # 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 - - -# TODO: Now calculate the amount of time until April Fool's Day - +if aprilFoolsDay < today: + print( + "April fools' day already went by, {} day(s) ago" + .format((today - aprilFoolsDay).days) + ) + aprilFoolsDay = aprilFoolsDay.replace(year=today.year + 1) + +# TODO: Now calculate the amount of time until April Fool's Day +time_to_afd = aprilFoolsDay - today +print("It is {} days until next april fools' day".format(time_to_afd.days)) diff --git a/Ch5 - Internet Data/htmlparsing_finished.py b/Ch5 - Internet Data/htmlparsing_finished.py deleted file mode 100644 index 48fa8fe..0000000 --- a/Ch5 - Internet Data/htmlparsing_finished.py +++ /dev/null @@ -1,58 +0,0 @@ -# -# Example file for parsing and processing HTML -# LinkedIn Learning Python course by Joe Marini -# - -# import the HTMLParser module -# in Python 3 you need to import from html.parser -from html.parser import HTMLParser - -paragraphs = 0 - -# create a subclass of HTMLParser and override the handler methods -class MyHTMLParser(HTMLParser): - # function to handle an opening tag in the doc - # this will be called when the closing ">" of the tag is reached - def handle_starttag(self, tag, attrs): - global paragraphs - if tag == "p": - paragraphs += 1 - - print ("Encountered a start tag:", tag) - pos = self.getpos() # returns a tuple indication line and character - print ("\tAt line: ", pos[0], " position ", pos[1]) - - if attrs.__len__() > 0: - print ("\tAttributes:") - for a in attrs: - print ("\t", a[0],"=",a[1]) - - # function to handle character and text data (tag contents) - def handle_data(self, data): - if (data.isspace()): - return - print ("Encountered some text data:", data) - pos = self.getpos() - print ("\tAt line: ", pos[0], " position ", pos[1]) - - # function to handle the processing of HTML comments - def handle_comment(self, data): - print ("Encountered comment:", data) - pos = self.getpos() - print ("\tAt line: ", pos[0], " position ", pos[1]) - -def main(): - # instantiate the parser and feed it some HTML - parser = MyHTMLParser() - - # open the sample HTML file and read it - f = open("samplehtml.html") - if f.mode == "r": - 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/htmlparsing_start.py b/Ch5 - Internet Data/htmlparsing_start.py index a759ac3..35dc0a0 100644 --- a/Ch5 - Internet Data/htmlparsing_start.py +++ b/Ch5 - Internet Data/htmlparsing_start.py @@ -1,29 +1,53 @@ -# +# # 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: '{}'".format(data)) + pos = self.getpos() + print("At line {}, position {}".format(pos[0], pos[1])) def handle_starttag(self, tag, attrs): - pass + print("Encountered a start tag: '{}'".format(tag)) + pos = self.getpos() + print("At line {}, position {}".format(pos[0], pos[1])) + + global paragraphs + if tag == "p": + paragraphs += 1 + + if len(attrs) > 0: + print("Attributes:") + for att in attrs: + print("\t{} = {}".format(att[0], att[1])) def handle_data(self, data): - pass + if (data.isspace()): + return + + print("Encountered text data: {}".format(data)) + pos = self.getpos() + print("At line {}, position {}".format(pos[0], 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) + contents = f.read() # read the entire file + parser.feed(contents) + + print("Paragraphs tags: {}".format(paragraphs)) + if __name__ == "__main__": main() - \ No newline at end of file diff --git a/Ch5 - Internet Data/inetdata_finished.py b/Ch5 - Internet Data/inetdata_finished.py deleted file mode 100644 index 656ff92..0000000 --- a/Ch5 - Internet Data/inetdata_finished.py +++ /dev/null @@ -1,20 +0,0 @@ -# -# Example file for retrieving data from the internet -# LinkedIn Learning Python course by Joe Marini -# - -import urllib.request # instead of urllib2 like in Python 2.7 - -def main(): - # open a connection to a URL using urllib2 - webUrl = urllib.request.urlopen("http://www.google.com") - - # get the result code and print it - print ("result code: ", webUrl.getcode()) - - # read the data from the URL and print it - data = webUrl.read() - print (data) - -if __name__ == "__main__": - main() diff --git a/Ch5 - Internet Data/inetdata_start.py b/Ch5 - Internet Data/inetdata_start.py index 86dc094..e4417a3 100644 --- a/Ch5 - Internet Data/inetdata_start.py +++ b/Ch5 - Internet Data/inetdata_start.py @@ -1,10 +1,18 @@ -# -# 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 + # open a connection to a URL using urllib2 + url = "https://google.com" + weburl = urllib.request.urlopen(url) + + # get the result code and print it + print("GET {} {}".format(url, weburl.getcode())) + + # read the data from the URL and print it + data = weburl.read() + print("PAYLOAD {}".format(data)) + if __name__ == "__main__": main() diff --git a/Ch5 - Internet Data/jsondata_finished.py b/Ch5 - Internet Data/jsondata_finished.py deleted file mode 100644 index d244ebf..0000000 --- a/Ch5 - Internet Data/jsondata_finished.py +++ /dev/null @@ -1,63 +0,0 @@ -# -# Example file for parsing and processing JSON -# LinkedIn Learning Python course by Joe Marini -# - - -import urllib.request # instead of urllib2 like in Python 2.7 -import json - - -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 - if "title" in theJSON["metadata"]: - print(theJSON["metadata"]["title"]) - - # output the number of events, plus the magnitude and each event name - count = theJSON["metadata"]["count"] - print(str(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.0: - print("%2.1f" % i["properties"]["mag"], i["properties"]["place"]) - print("--------------\n") - - # print only the events where at least 1 person reported feeling something - print("\n\nEvents that were felt:") - for i in theJSON["features"]: - feltReports = i["properties"]["felt"] - if (feltReports != None): - if (feltReports > 0): - print("%2.1f" % 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 = "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())) - if (webUrl.getcode() == 200): - data = webUrl.read().decode("utf-8") - # print out our customized results - printResults(data) - else: - print("Received an error from server, cannot retrieve results " + - str(webUrl.getcode())) - - -if __name__ == "__main__": - main() diff --git a/Ch5 - Internet Data/jsondata_start.py b/Ch5 - Internet Data/jsondata_start.py index e0da623..adf19bb 100644 --- a/Ch5 - Internet Data/jsondata_start.py +++ b/Ch5 - Internet Data/jsondata_start.py @@ -1,39 +1,72 @@ -# -# Example file for parsing and processing JSON -# LinkedIn Learning Python course by Joe Marini -# +import urllib.request +import json -import urllib.request def printResults(data): # Use the json module to load the string data into a dictionary - theJSON = json.loads(data) - + content = json.loads(data) + # now we can access the contents of the JSON like any other Python object + if "metadata" in content and "title" in content["metadata"]: + print(content["metadata"]["title"]) + print("---------------------------------------------\n") - - # output the number of events, plus the magnitude and each event name + # output the number of events, plus the magnitude and each event name + if "metadata" in content and "count" in content["metadata"]: + print("{} event(s) recorded".format(content["metadata"]["count"])) + print("---------------------------------------------\n") - # for each event, print the place where it occurred - + if "features" in content: + for event in content["features"]: + if "properties" in event and "place" in event["properties"]: + print(event["properties"]["place"]) + print("---------------------------------------------\n") # print the events that only have a magnitude greater than 4 - + print("Events with magnitude greater than 4:\n") + if "features" in content: + for event in content["features"]: + if "properties" in event and "mag" in event["properties"] and event["properties"]["mag"] > 4: + print("{}, Magnitude {}".format( + event["properties"]["place"], + event["properties"]["mag"] + )) + print("---------------------------------------------\n") # print only the events where at least 1 person reported feeling something + print("Events that were felt by someone:\n") + if "features" in content: + for event in content["features"]: + if "properties" in event and "felt" in event["properties"]: + felt = event["properties"]["felt"] + if felt and int(felt) > 0: + print("{}, felt {} time{}".format( + event["properties"]["place"], + felt, + "s" if felt > 1 else "" + )) + print("---------------------------------------------\n") + - 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" + url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" + + try: + # Open the URL and read the data + website = urllib.request.urlopen(url) + httpStatus = website.getcode() + print("GET {} {}".format(url, httpStatus)) + if httpStatus == 200: + printResults(website.read()) + else: + print("Received HTTP status {} from the server.".format(httpStatus)) + except Exception as e: + print("Error opening website {}:\n{}".format(url, e)) - # Open the URL and read the data - webUrl = urllib.request.urlopen(urlData) - print ("result code: " + str(webUrl.getcode())) - if __name__ == "__main__": main() diff --git a/Ch5 - Internet Data/samplehtml.html b/Ch5 - Internet Data/samplehtml.html index 594b35e..ed4cf34 100644 --- a/Ch5 - Internet Data/samplehtml.html +++ b/Ch5 - Internet Data/samplehtml.html @@ -1,12 +1,15 @@ -
-This is some text
- - + + +This is some text
+ + + diff --git a/Ch5 - Internet Data/xmlparsing_finished.py b/Ch5 - Internet Data/xmlparsing_finished.py deleted file mode 100644 index bfc0309..0000000 --- a/Ch5 - Internet Data/xmlparsing_finished.py +++ /dev/null @@ -1,35 +0,0 @@ -# -# 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 ("%d skills:" % skills.length) - 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 ("%d skills:" % skills.length) - for skill in skills: - print (skill.getAttribute("name")) - -if __name__ == "__main__": - main() - diff --git a/Ch5 - Internet Data/xmlparsing_start.py b/Ch5 - Internet Data/xmlparsing_start.py index 3129b0c..00ca899 100644 --- a/Ch5 - Internet Data/xmlparsing_start.py +++ b/Ch5 - Internet Data/xmlparsing_start.py @@ -1,23 +1,31 @@ -# -# 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(doc.nodeName) + print(doc.firstChild.tagName) + print("---------------------------------------------\n") - # print out the document node and the name of the first child tag - + skills = doc.getElementsByTagName("skill") + print("{} skills are listed".format(skills.length)) + for skill in skills: + print(skill.getAttribute("name")) + print("---------------------------------------------\n") # get a list of XML tags from the document and print each one + newSkill = doc.createElement("skill") + newSkill.setAttribute("name", "jQuery") + doc.firstChild.appendChild(newSkill) - # create a new XML tag and add it into the document + skills = doc.getElementsByTagName("skill") + print("{} skills are listed".format(skills.length)) + for skill in skills: + print(skill.getAttribute("name")) - if __name__ == "__main__": main() -