Coding

Automating Simple Tasks with Python: Using Python and Window Task Scheduler to get the word of the day

Learning is a treasure that will follow its owner everywhere.❞‒Chinese Proverb

So I want to learn one english word per day, but I am too lazy and forgetful to visit the website ? Hmm…. bulb floats on head

Let us create a python script, that runs daily by the Windows Task Scheduler

12:16:00 AM Coffee break…


In this blog post, I will be describing my thought process of solving this problem and providing the code.

Hopefully it helps.

Before I begin, what have I learned:

  1. Knowing Code is awesome!
  2. Python Desktop application development is possible
  3. Using Task Scheduler to execute a program
  4. With this, I can basically automate the backup of my websites / web apps  and many more

Thought Process 

Word of the day Website

  • Create a function that crawls the website, extracts the word, its definition and examples, after which transforms the data into a dictionary.

[sourcecode lang=”python”]

#USAGE: python wordofday.py

#TODO: create function to crawl the website
#TODO: create function to display the word, definition and examples in a notepad

import requests, logging, os
from bs4 import BeautifulSoup

filepath = os.path.abspath("C:\\users\\ajala\\desktop\\word.txt")
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s – %(levelname)s – %(message)s")
def crawl_web():
url = "http://www.wordnik.com/word-of-the-day"
dictionary = {}
try:
#make request
res = requests.get(url)
#raise status
res.raise_for_status()
content = res.text
#create soup
soup = BeautifulSoup(content, "html.parser")
try:
content_column = soup.find("div", {"class":"content_column"})
try:
word_of_day = content_column.find("h1")
word_of_day = word_of_day.find("a").get_text()
dictionary["word"] = word_of_day
#get all definitions
try:
dictionary["definitions"] = []
def_soup = content_column.find_all("abbr", {"title":"partOfSpeech"})
for definition in def_soup:
d = definition.find_parent("li").get_text()
dictionary["definitions"].append( d )
#get all examples
try:
dictionary["examples"] = []
ex_soup = content_column.find_all("li", {"class":"exampleItem"})
for example in ex_soup:
e = example.find("p", {"class":"text"}).get_text()
dictionary["examples"].append(e)
return save_word_of_day(dictionary)
except Exception as exErr:
logging.error("Error while finding examples: " + str(exErr))
except Exception as defErr:
logging.error("Error while finding definitions: " + str(defErr))
except Exception as wErr:
logging.error("Error while finding word of day: " + str(wErr))
except Exception as cErr:
logging.error("Error while finding content column: " + str(cErr))
except Exception as err:
logging.error("Error while making request: " + str(err))<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>
[/sourcecode]

  • Create a function that saves the data into  a .txt file

[sourcecode lang=”python”]

def save_word_of_day(dictionary:dict):
#save the word of the day
global filepath
try:
fh = open(filepath, "w")
#write word
fh.write(dictionary["word"] + "\n")
fh.write("-"*10)
fh.write("\n\n")
fh.write("Definition\n")
fh.write("–"*10)
fh.write("\n\n")
#prints all definitions
for pos in range(len(dictionary["definitions"])):
de = dictionary["definitions"][pos]
fh.write(str( pos + 1) + ".\t" + de)
fh.write("\n")
fh.write("\n\n")
fh.write("Examples\n")
fh.write("–"*10)
fh.write("\n\n")
for pos in range(len(dictionary["examples"])):
ex = dictionary["examples"][pos]
fh.write(str( pos + 1) + ".\t" + ex)
fh.write("\n")
logging.info("closing file: " + filepath)
fh.close()
display_in_notepad()
except Exception as err:
logging.error("Error while creating file: " + str(err))<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>
[/sourcecode]

  • Create a function that opens the saved file using the default application

[sourcecode lang=”python”]
def display_in_notepad():
#open the wordpad
global filepath
##create alarm before opening file
os.system("start " + filepath)
return

if __name__ == "__main__":
crawl_web()
[/sourcecode]

  • Add the task in the Task Scheduler
    • Create New Task
    • Add Task information e.g. Name, Description
      • D
    • Define an action –> which specifies what program should be ran and how
        • I set “program/script” to the python.exe file, so you have to find the file in your own system
        • The arguments for the python is the wordofday script, which is located in the root directory “C:\\”
      • Define the trigger –> specifies when and how often the program is to be run or “triggered”
          • I set mine to once daily at 7:00 am
      • Click ok. Done!
  • Complete

 

How do I plan to make this better ?

  1. Execute a music player before the wordpad is opened. This acts like an alarm, which signals that “it is time to learn the word of the day”.
  2. Create a desktop application, that displays the word of the day and its content without using the wordpad application.

To see how I coded it, watch the following three part streaming videos.

 

 

 

 

IF you have suggestions, provide them in the comment section..

See ya!

Please follow and like us:
0

Enjoy this blog? Please spread the word :)

error: Content is protected !!