Posts

Showing posts from April, 2019

Python Parse XML

Below code shows how to parse an XML document in Python. XML document simplexml.xml < ?xml version = "1.0" encoding = "UTF-8" ? > < person > < firstname > Joe < / firstname > < lastname > Marini < / lastname > < home > Seattle < / home > < skill name = "JavaScript" / > < skill name = "Python" / > < skill name = "C#" / > < skill name = "HTML" / > < / person > Python XML parser code # # Python parse xml # 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 . getElementsByTagN

Python Parse HTML

How to parse HTML using Python and HTMLparser library. # # Python parse HTML # from html . parser import HTMLParser class AnHTMLParser ( HTMLParser ) : def handle_comment ( self , data ) : print ( "Encountered comment: " , data ) pos = self . getpos ( ) print ( " \t At line: " , pos [ 0 ] , " position " , pos [ 1 ] ) def main ( ) : # instantiate the parser and feed it some HTML parser = AnHTMLParser ( ) f = open ( "samplehtml.html" ) if f . mode == 'r' : contents = f . read ( ) print ( contents ) parser . feed ( contents ) if __name__ == "__main__" : main ( ) ; -------------------------------------------------- #Output <!DOCTYPE html> <html lang="en">   <head>     <meta charset="utf-8" />     <title>Sample HTML Document</title>     <meta name="description" content="

Python Parsing JSON Url Example

The code below show an example of how to parse JSON data from a url using Python. In this case we are fetching current earthquake data from a url feed. # # Python parsing JSON url example # import urllib . request 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" ] ) # 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 ( "-------------------------" ) # print th

Python urllib Example

Below code shows how to use urllib Python library to read content of a url. # # Python urllib example # import urllib . request def main ( ) : webUrl = urllib . request . urlopen ( "http://www.google.com" ) print ( "request code: " + str ( webUrl . getcode ( ) ) ) data = webUrl . read ( ) print ( data ) if __name__ == "__main__" : main ( ) ------------------------------------------ #Output request code: 200 b'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type&q

Python Copy File

The code below shows how to copy and rename file in Python programming language.  A copy of textfile.txt will created and appended a .bak extension. The file will then be renamed using Python os path. # # Python Copy File # import os from os import path import shutil 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" # copy over the permissions, modification times, and other info shutil . copy ( src , dst ) shutil . copystat ( src , dst ) # rename the original file os . rename ( "textfile.txt" , "newfile.txt" ) if __name__ == "__main__" : main ( )

Python OS Path

The example code below shows how to manipulate Python os path. # # Python OS path examples # 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 ) print ( "Items exists: " + str ( path . exists ( "textfile.txt" ) ) ) print ( "Itrm s a file: " + str ( path . isfile ( "textfile.txt" ) ) ) print ( "Itrm s a directory: " + str ( path . isdir ( "textfile.txt" ) ) ) # Work with file paths print ( "Item path: " + str ( path . realpath ( "textfile.txt" ) ) ) print ( "Item path and name: " + str ( path . realpath ( "textfile.txt" ) ) ) # Get the modification time t = time . ctime ( path . getmtime ( "textfile.txt" ) ) print ( "Last modified" , t ) print ( "Last modified" , datetime . dateti

Python Read File

The code below shows 2 ways to read file in Python. 1. Read all contents 2. Read line by line # # Python Read File # def main ( ) : f = open ( "textfile.txt" , "r" ) #1 Read contents if f . mode == "r" : contents = f . read ( ) print ( contents ) #2 Read line by line if f . mode == "r" : fl = f . readline ( ) for x in fl : print ( x ) if __name__ == "__main__" : main ( ) ------------------------------------------- #Output This is a line 0 This is a line 1 This is a line 2 This is a line 3 This is a line 4 This is a line 5 This is a line 6 This is a line 7 This is a line 8 This is a line 9 This is a line 10 This is a line 11 This is a line 12 This is a line 13 This is a line 14 This is a line 0 This is a line 1 This is a line 2 This is a line 3 This is a line 4 This is a line 5 This is a line 6 This is a line 7

Python Append To File

The code below is an example on how to append to an existing file using Python. The textfile will result in text being appended at the end. # # Python Append To File # def main ( ) : #Append to an already created file f = open ( "textfile.txt" , "a" ) # write some lines of data to the file for i in range ( 10 ) : f . write ( "This is a line " + str ( i ) + " \r \n " ) # close the file when done f . close ( ) if __name__ == "__main__" : main ( ) --------------------------------------- textfile.txt This is a line 0 This is a line 1 This is a line 2 This is a line 3 This is a line 4 This is a line 5 This is a line 6 This is a line 7 This is a line 8 This is a line 9 This is a line 10 This is a line 11 This is a line 12 This is a line 13 This is a line 14 This is a line 0 This is a line 1 This is a line 2 This is a line 3 This is a line 4 This is a line 5 T

Python Write To File Example

The code below shows how to write to a file using Python. The textfile.txt will be created and the data written as shown in output below. # # Python Write To File # def main ( ) : # Open a file for writing and create it if it doesn't exist f = open ( "textfile.txt" , "w+" ) # write some lines of data to the file for i in range ( 15 ) : f . write ( "This is a line " + str ( i ) + " \r \n " ) # close the file when done f . close ( ) if __name__ == "__main__" : main ( ) ------------------------------------------------------ Contents of textfile.txt This is a line 0 This is a line 1 This is a line 2 This is a line 3 This is a line 4 This is a line 5 This is a line 6 This is a line 7 This is a line 8 This is a line 9 This is a line 10 This is a line 11 This is a line 12 This is a line 13 This is a line 14

Python Calendar Example

Below code demonstrated working with calendar using Python. # # Python calendar example # # import the calendar module import calendar # create a plain text calendar c = calendar . TextCalendar ( calendar . SUNDAY ) st = c . formatmonth ( 2019 , 1 , 1 , 0 ) print ( st ) # create an HTML formatted calendar hc = calendar . HTMLCalendar ( calendar . SUNDAY ) st = hc . formatmonth ( 2019 , 1 ) print ( st ) #Prints html table based calendar # 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 ( 2019 , 5 ) : 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 ) --------------------------------------------- #Output January 2019 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1

Python Timedelta Example

Below code show how to use timedelta in Python to add and subtract day and time. # # Python timedelta # from datetime import date 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's date: " , str ( now ) ) print ( "One year from now will be: " , str ( now + timedelta ( days = 365 ) ) ) print ( "In 2 days it will be: " , str ( now + timedelta ( days = 2 ) ) ) print ( "In 3 weeks it will be: " , str ( now + timedelta ( weeks = 3 ) ) ) print ( "1 week ago it was: " , str ( now - timedelta ( weeks = 1 ) ) ) ### How many days until Christmas day Day of current year today = date . today ( ) christmas_day = date ( today . year , 12 , 25 ) print ( "Days till Christmas: " , str ( christmas_day - today ) ) ---

Python strftime Example

Below code demonstrated the use of strftime method to format time using Python. # # Python strftime Example # from datetime import datetime def main ( ) : # Times and dates can be formatted using a set of predefined string now = datetime . now ( ) print ( now . strftime ( "%a, %d %B, %Y" ) ) print ( now . strftime ( "Local date and time: %c" ) ) #Local date and time print ( now . strftime ( "Local date: %x" ) ) #Local date print ( now . strftime ( "Local time: %X" ) ) #Local time print ( now . strftime ( "Current time: %I:%M:%S %p" ) ) print ( now . strftime ( "24-hour time: %H:%M" ) ) if __name__ == "__main__" : main ( ) ; ---------------------------------------------------- #Output Sat, 20 April, 2019 Local date and time: Sat Apr 20 11:46:31 2019 Local date: 04/20/19 Local time: 11:46:31 Current time: 11:46:31 AM 24-hour time:  11:46

Python Datetime Example

Python Datetime Example using date and datetime Python libraries. # # Python Datetime Example # from datetime import date from datetime import datetime def main ( ) : ## DATE OBJECTS today = date . today ( ) print ( "Today's date is: " , today ) print ( "Date components: " , today . month , today . day , today . year ) print ( "Today's weekday number is: " , today . weekday ( ) ) days = [ "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday" ] print ( "Which is a: " + days [ today . weekday ( ) ] ) ## DATETIME OBJECTS today1 = datetime . now ( ) print ( "The current date and time is: " , today1 ) time = datetime . time ( datetime . now ( ) ) print ( "Current time: " , time ) if __name__ == "__main__" : main ( ) ; ---------------

Python Class And Methods

Python class and methods are defined as shown in the code below. # # Python class and methods # class myClass ( ) : def method1 ( self ) : print ( "method1" ) def method2 ( self , someString ) : print ( "method2 " + someString ) def main ( ) : c = myClass ( ) c . method1 ( ) c . method2 ( "Hello World!" ) if __name__ == "__main__" : main ( ) -------------------------------------------- #Output method1 method2 Hello World!

Python Enumerate For

The enumerate function in Python is used to get the index of the items in an iterable. The Python Enumerate for, adds a counter to the for loop as show in the example below. #Python enumerate for days = [ "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" ] for index , day in enumerate ( days ) : print ( index , day ) ----------------------------------------------------- #Output 0 Monday 1 Tuesday 2 Wednesday 3 Thursday 4 Friday

Python Continue Statement

Below code demonstrates how to use the Python continue statement. #Python continue statement for i in range ( 2 , 11 ) : if i == 7 : #Will skip 7 and continue continue print ( i ) ------------------------------------------- #Output 2 3 4 5 6 8 9 10

Python Break Statement

You can use the Python break statement to jump out of a Python looping code. Example is when using the for loop as shown below. #Python break statement for i in range ( 2 , 11 ) : if i == 7 : break print ( i ) ------------------------------------------------ #Ouput 2 3 4 5 6

Python For Loop List

Python For Loop List Code. #Python for loop for list breakfast_items = [ "Eggs" , "Bread" , "Milk" , "Coffee" , "Tea" ] for item in breakfast_items : print ( item ) ------------------------------------------------ #Output Eggs Bread Milk Coffee Tea

Python For Loop

Below code demonstrated using Python for loop. #Python for loop def main ( ) : x = 0 #define for loop for x in range ( 5 , 10 ) : print ( x ) if __name__ == "__main__" : main ( ) ---------------------------------------------- #Output 5 6 7 8 9

Python While Loop

Below code demonstrates using a Python while loop. #Python while loop def main ( ) : x = 0 #define while loop while ( x < 5 ) : print ( x ) x = x + 1 if __name__ == "__main__" : main ( ) ------------------------------------------------ #Output 0 1 2 3 4

Python Find Max Value In List

Below code is used to find max value in list using Python. #Python find max value in list items = [ 5 , 6 , 34 , 55 , 43 , 48 , 505 , 32 , 54 , 88 , 90 ] def find_max ( items_list ) : #return last item in list: breaking condition if len ( items_list ) == 1 : return items_list [ 0 ] #Otherwise get the first item and call function #Iterate to the rest of list opt1 = items_list [ 0 ] opt2 = find_max ( items_list [ 1 : ] ) #Compare when done if opt1 > opt2 : return opt1 else : return opt2 print ( find_max ( items ) ) ------------------------------------------------------------------------------------------------ #Output 505

Python dictionary count values

#Python dictionary count values by key items = [ "Banana" , "Apple" , "Avocado" , "Grapes" , "Oranges" , "Banana" , "Apple" , "Avocado" , "Kiwi" , "Pear" ] #hash table object to hold the items and count counter = dict ( ) #loop over each and increment by 1 for item in items : if item in counter . keys ( ) : counter [ item ] + = 1 else : counter [ item ] = 1 print ( counter ) ------------------------------------------------------------------------------------------------------- #Output {'Banana': 2, 'Apple': 2, 'Avocado': 2, 'Grapes': 1, 'Oranges': 1, 'Kiwi': 1, 'Pear': 1}

Python filter list using hash table

Python filter list using a hash table #Python filter list using hash table items = [ "Banana" , "Apple" , "Avocado" , "Grapes" , "Oranges" , "Banana" , "Apple" , "Avocado" , "Kiwi" , "Pear" ] #Hash table to perform filter filter = dict ( ) #Loop over each hash table and add to the hash table for key in items : filter [ key ] = 0 #Create a set from the resulting hash table result = set ( filter . keys ( ) ) print ( result ) #This filter takes time to go through each loop depending on the size of the list items to filter ------------------------------------------------------------------------------------------------------------------------- #Output {'Apple', 'Oranges', 'Banana', 'Grapes', 'Kiwi', 'Avocado', 'Pear'}