Python Tricks A Buffet Of Awesome Python Features Pdf Download
Introduction
In a world where AI, ML, and Data Science are the dominant technologies these days, all the mentioned technologies are dependent on the Python programming linguistic communication in some or the another fashion. Then becoming a master in Python can open many doors in your career and land in some of the all-time opportunities across the planet.
I am hoping you every bit a reader here is either starting time in Python or practicing to become an proficient or maybe challenging your skills with fifty-fifty harder issues to piece of work on with Python. No thing wherever you rate yourself in the Python skill, trying to work on Python projects would definitely uplift your skills and build up your profile to confront the competitive earth exterior. Although, Python books and Python tutorials are pretty helpful to and provide quite detailed cognition of the ultimate test of your learning would come up from the capability that you lot can code and create something of your own.
Before jumping right into the project ideas let united states of america read how tin Python projects help you as a Python developer and which platform y'all should consider before y'all beginning any Python projects.
How Tin Python Projects Assistance You?
Challenging your learning and edifice Python projects can help you in multiple ways some of them are listed below:
Boost Up Your Confidence
Doing up things yourself and in your way using tools and technologies would build up your confidence. It would also assistance youtube rate your skill as a Python developer to assistance me perform amend.
Explore and Experiment
Edifice projects would give an opportunity to acquaint yourself with the trending tools and applied science that are required for your projection. You lot may get your skills in servers, databases, UI concepts, and more.
Master your Coding Skills
Projection is another name for practice and we know do is the mantra to excel in anything. In one case you are well versed in Python coding and other dependencies that a Python project requires you shall notice how efficient you become as yous climb the ladder of challenging projects.
Learn nearly Software Evolution Lifecycle
This step is of import to exist learned when yous retrieve you are industry-ready and that you are capable of taking upwardly real-life projects. You must learn to develop a project in an optimized and organized manner as the SDLC paradigm.
Which Project Platform Should Yous Use?
Subsequently y'all are all set and motivated to build a project, you must call back of what to build and on which platform to build your Python project. You must build what interests you irrespective of if information technology is trending or non or requires a less or massive amount of coding skill level. It would exist hard to stay on a project or even finish information technology if you kickoff with something that doesn't interest yous.
There are three major platforms where you can start building your project, let us have an overview of them:
1. Spider web
Web applications run on the web and can run on whatever device without being downloaded; the but requirement is that there should be an accessible net. Web applications take the frontend and backend. The front end is responsible for the UI of the website. Later is where business organization logic takes place, and the code manipulation and information storage occur.
A Python developer majorly focuses on backend code. The front end end is essential, too, and so a Python developer must have some knowledge of HTML, CSS, and Javascript to create simple looking AI. With an extra library, a Python developer can utilise Python for both the back and front end end of their Python projects. Django and Flask are pop web frameworks to build applications using Python.
2. Desktop UI
Edifice Desktop Awarding in Python is a neat project idea for beginners as well as for intermediate learners. The skilful news for python developers is that they exercise non require to larn any Atomic number 26 engineering science to develop a desktop python project. There exist several frameworks for edifice desktop applications. PySimple GUI is a convenient Python Framework, PyQt5 is an avant-garde python based GUI framework. A fully adult desktop can later be made uniform with all major Bone (Linux, Windows, or macOS).
iii. Control Line
In Command-Line Applications, user interaction is entirely dependent on the concluding & shell. The command-line applications part in a console window and are devoid of any class of graphics and visual interface for the users to see. A Python programmer has to enter specific commands, while the user provides the input to the application using ASCII characters, the app provides the output through ASCII.
Command-Line applications are robust and powerful but are not user friendly as web or desktop applications click, Docopt, Plac, Cliff, are some of the control-line frameworks for Python
Gear up and be motivated to endeavour the beneath mentioned Python projects.
Beginner Level Python Project Ideas
Hither we have listed python projects for beginners level Python Developer.
i. Mad Libs Generator
This python beginner projection is a practiced start for beginner software developers as it has concepts like strings, variables, and concatenation. Mad Libs Generator teaches to manipulate user-inputted information equally the Mad Libs refer to a series of inputs that a user enters. The input from the user could be anything from an adjective, a pronoun, or even a verb. Afterward all the inputs are entered the awarding takes all the data and arranges it to build a story template.
Source Code:
""" Mad Libs Generator
----------------------------------------
"""
//Loop dorsum to this point once code finishes
loop = 1
while (loop < ten):
// All the questions that the programme asks the user
noun = input("Cull a substantive: ")
p_noun = input("Cull a plural noun: ")
noun2 = input("Choose a noun: ")
place = input("Name a place: ")
adjective = input("Choose an adjective (Describing word): ")
noun3 = input("Choose a noun: ")
// Displays the story based on the users input
print ("------------------------------------------")
print ("Exist kind to your",noun,"- footed", p_noun)
print ("For a duck may be somebody's", noun2,",")
print ("Be kind to your",p_noun,"in",identify)
impress ("Where the atmospheric condition is ever",adjective,".")
print ()
print ("You may recall that is this the",noun3,",")
print ("Well it is.")
impress ("------------------------------------------")
// Loop back to "loop = 1"
loop = loop + 1
2. Number Guessing
This projection is an exciting fun game for beginners to build upward. The programme generates a random number from 1 to 10, or one to 100 whatever range that is specified and the user must gauge the number later a hint from the computer. Every time a user's guess is wrong they are prompted with more hints to get in easier for them to estimate the number merely at the cost of reducing the score. The clue any math clue like multiples, divisible, greater or smaller, or a combination of all.
The program also requires functions to bank check if an actual number is entered by the user or non, to compare the input number with the actual number, to find the divergence between the two numbers.
Sample Code:
""" Number Guessing Game
----------------------------------------
"""
import random
attempts_list = []
def show_score():
if len(attempts_list) <= 0:
print("In that location is currently no loftier score, it's yours for the taking!")
else:
impress("The electric current high score is {} attempts".format(min(attempts_list)))
def start_game():
random_number = int(random.randint(1, x))
print("Hi traveler! Welcome to the game of guesses!")
player_name = input("What is your name? ")
wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))
// Where the show_score function USED to be
attempts = 0
show_score()
while wanna_play.lower() == "aye":
try:
approximate = input("Choice a number between i and x ")
if int(guess) < one or int(guess) > ten:
raise ValueError("Please judge a number within the given range")
if int(gauge) == random_number:
print("Squeamish! You got it!")
attempts += one
attempts_list.append(attempts)
print("Information technology took you lot {} attempts".format(attempts))
play_again = input("Would you similar to play once again? (Enter Yeah/No) ")
attempts = 0
show_score()
random_number = int(random.randint(1, ten))
if play_again.lower() == "no":
print("That's cool, have a good 1!")
break
elif int(approximate) > random_number:
impress("It'south lower")
attempts += 1
elif int(approximate) < random_number:
print("It's higher")
attempts += i
except ValueError as err:
print("Oh no!, that is not a valid value. Endeavour again...")
impress("({})".format(err))
else:
print("That's cool, accept a skillful one!")
if __name__ == '__main__':
start_game()
3. Stone Paper Scissors
This plan or a mini-game is designed when y'all don't accept anyone to play or you are under lockdown alone. There are a number of functions that this program requires and so permit u.s.a. have an overview of each.
- a random function: to generate rock, paper, or scissors.
- valid function: to cheque the validity of the motility.
- result function: to declare the winner of the round.
- scorekeeper: to continue track of the score.
The program requires the user to make the first move before information technology makes i the motion. One time the movement is validated the input is evaluated, the input entered could exist a string or an alphabet. After evaluating the input string a winner is decided by the effect function and the score of the circular is updated by the scorekeeper office.
Sample Code:
""" Stone Paper Scissors
----------------------------------------
"""
import random
import os
import re
os.arrangement('cls' if os.proper name=='nt' else 'articulate')
while (1 < 2):
print "\n"
print "Rock, Newspaper, Pair of scissors - Shoot!"
userChoice = raw_input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")
if not re.friction match("[SsRrPp]", userChoice):
impress "Delight choose a letter:"
print "[R]ock, [S]cissors or [P]aper."
proceed
// Echo the user'southward selection
print "You chose: " + userChoice
choices = ['R', 'P', 'S']
opponenetChoice = random.choice(choices)
print "I chose: " + opponenetChoice
if opponenetChoice == str.upper(userChoice):
impress "Tie! "
#if opponenetChoice == str("R") and str.upper(userChoice) == "P"
elif opponenetChoice == 'R' and userChoice.upper() == 'S':
print "Scissors beats rock, I win! "
continue
elif opponenetChoice == 'Southward' and userChoice.upper() == 'P':
print "Scissors beats newspaper! I win! "
proceed
elif opponenetChoice == 'P' and userChoice.upper() == 'R':
print "Paper shell rock, I win! "
keep
else:
print "You win!"
4. Website Blocker
We all know while surfing through the cyberspace many unwanted sites popup to distract the states. This project comes at help in such cases as it can exist built up to block certain websites from opening. The program is benign for people who get easily distracted to switch to social media sites while into something serious.
Sample Code:
""" Website Blocker
----------------------------------------
"""
import time
from datetime import datetime equally dt
hosts_path = r"/etc/hosts" // r is for raw string
hosts_temp = "hosts"
redirect = "127.0.0.ane"
web_sites_list = ["www.facebook.com", "facebook.com"] // users tin can change the list of the websites they want to cake
while True:
if dt(dt.at present().year, dt.at present().calendar month, dt.now().twenty-four hours, ix) < dt.at present() < dt(dt.now().yr, dt.now().month, dt.now().day,22):
print("Working hours")
with open(hosts_path, "r+") as file:
content = file.read()
for website in web_sites_list:
if website in content:
pass
else:
file.write(redirect+" "+website+"\n")
else:
impress("Fun time")
with open(hosts_path, "r+") every bit file:
content = file.readlines()
file.seek(0) // reset the arrow to the elevation of the text file
for line in content:
// here comes the tricky line, basically we overwrite the whole file
if not any(website in line for website in web_sites_list):
file.write(line)
// exercise nothing otherwise
file.truncate() // this line is used to delete the trailing lines (that contain DNS)
fourth dimension.sleep(5)
v. Binary Search Algorithm
The proper noun is axiomatic enough to requite an overview of the project. The programme requires you to create a list of numbers between 0 to whatever range you prefer, with every succeeding number having a difference of 2 betwixt them.
When the user inputs a random number to be searched the program begins its search by dividing the list into ii halves. The first half is searched for the required number and if constitute, the other half is rejected and vice versa. The search continues until the number is found or the subarray size becomes zero. This Python project idea could besides aid you write a program to search an element in the listing.
Sample Code:
""" Binary Search Algorithm
----------------------------------------
"""
// iterative implementation of binary search in Python
def binary_search(a_list, particular):
"""Performs iterative binary search to notice the position of an integer in a given, sorted, list.
a_list -- sorted listing of integers
item -- integer you are searching for the position of
"""
first = 0
final = len(a_list) - 1
while outset <= final:
i = (first + last) / ii
if a_list[i] == particular:
return ' establish at position '.format(particular=item, i=i)
elif a_list[i] > item:
concluding = i - one
elif a_list[i] < item:
start = i + 1
else:
return ' not found in the list'.format(particular=particular)
// recursive implementation of binary search in Python
def binary_search_recursive(a_list, item):
"""Performs recursive binary search of an integer in a given, sorted, list.
a_list -- sorted list of integers
detail -- integer you lot are searching for the position of
"""
first = 0
last = len(a_list) - 1
if len(a_list) == 0:
render ' was not found in the listing'.format(detail=detail)
else:
i = (starting time + last) // 2
if item == a_list[i]:
render ' plant'.format(particular=item)
else:
if a_list[i] < item:
return binary_search_recursive(a_list[i+one:], item)
else:
return binary_search_recursive(a_list[:i], item)
1. Reckoner
Building this projection you would learn to design a graphical UI and make y'all familiar with a library like Tkinter. This library enables you to create buttons to perform different operations and brandish results on the screen.
Sample Code:
""" Figurer
----------------------------------------
"""
def add-on ():
print("Addition")
due north = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 0
while n != 0:
ans = ans + n
t+=one
n = float(input("Enter another number (0 to calculate): "))
render [ans,t]
def subtraction ():
impress("Subtraction");
n = bladder(input("Enter the number: "))
t = 0 //Full number enter
sum = 0
while due north != 0:
ans = ans - n
t+=one
n = bladder(input("Enter another number (0 to calculate): "))
return [ans,t]
def multiplication ():
print("Multiplication")
n = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 1
while north != 0:
ans = ans * northward
t+=i
northward = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def average():
an = []
an = addition()
t = an[1]
a = an[0]
ans = a / t
render [ans,t]
// main...
while True:
list = []
print(" My first python program!")
print(" Simple Calculator in python by Malik Umer Farooq")
print(" Enter 'a' for addition")
print(" Enter 's' for substraction")
print(" Enter 'thou' for multiplication")
impress(" Enter '5' for boilerplate")
print(" Enter 'q' for quit")
c = input(" ")
if c != 'q':
if c == 'a':
listing = addition()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 's':
list = subtraction()
print("Ans = ", listing[0], " total inputs ",listing[1])
elif c == 'one thousand':
list = multiplication()
impress("Ans = ", listing[0], " total inputs ",list[1])
elif c == 'v':
list = average()
impress("Ans = ", list[0], " total inputs ",listing[one])
else:
print ("Sorry, invilid character")
else:
pause
ii. Alarm Clock
This is an interesting Command Line Interface (CLI) Python application for an intermediate-level developer. People across the earth use warning clock features in their devices only this projection tin can be contradistinct in a bit different manner. Some certain YouTube links can be added to a text file and the projection is programmed in a style that when a user sets an alert then the lawmaking shall pick a random link from the video and will outset playing the YouTube link.
Sample Code:
""" Alert Clock
----------------------------------------
"""
import datetime
import os
import time
import random
import webbrowser
// If video URL file does non exist, create one
if not bone.path.isfile("youtube_alarm_videos.txt"):
print('Creating "youtube_alarm_videos.txt"...')
with open("youtube_alarm_videos.txt", "w") as alarm_file:
alarm_file.write("https://www.youtube.com/watch?v=anM6uIZvx74")
def check_alarm_input(alarm_time):
"""Checks to see if the user has entered in a valid alert fourth dimension"""
if len(alarm_time) == 1: // [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return Truthful
if len(alarm_time) == 2: // [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0:
return True
elif len(alarm_time) == iii: // [Hr:Minute:Second] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0 and \
alarm_time[ii] < sixty and alarm_time[two] >= 0:
return True
return False
// Go user input for the alarm time
impress("Set a time for the alert (Ex. 06:30 or 18:30:00)")
while True:
alarm_input = input(">> ")
try:
alarm_time = [int(n) for n in alarm_input.split(":")]
if check_alarm_input(alarm_time):
break
else:
raise ValueError
except ValueError:
impress("ERROR: Enter time in HH:MM or HH:MM:SS format")
// Convert the alarm fourth dimension from [H:M] or [H:Thousand:South] to seconds
seconds_hms = [3600, lx, 1] // Number of seconds in an Hour, Infinitesimal, and Second
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
// Get the current time of day in seconds
now = datetime.datetime.now()
current_time_seconds = sum([a*b for a,b in nix(seconds_hms, [now.hour, now.infinitesimal, at present.2d])])
// Calculate the number of seconds until alarm goes off
time_diff_seconds = alarm_seconds - current_time_seconds
// If time departure is negative, set alarm for next day
if time_diff_seconds < 0:
time_diff_seconds += 86400 // number of seconds in a day
// Display the corporeality of time until the alarm goes off
print("Warning set to go off in %south" % datetime.timedelta(seconds=time_diff_seconds))
// Slumber until the alarm goes off
time.slumber(time_diff_seconds)
// Time for the alarm to become off
print("Wake Up!")
// Load list of possible video URLs
with open("youtube_alarm_videos.txt", "r") as alarm_file:
videos = alarm_file.readlines()
// Open up a random video from the listing
webbrowser.open up(random.choice(videos))
3. Tic- Tac- Toe
This game is very pop amongst all of the states and even fun to build as a Python project. I am pretty sure most of united states know how to play information technology but permit me requite a quick castor upwards.
It is a two-player game and consists of a nine-square grid. Each role player chooses their movement and with O or 10 and marks their square one at each chance. The player who succeeds in making their marks all in one line whether diagonally, horizontally, or vertically wins. The claiming for the other player is to cake the game for their opponent and besides to make their concatenation.
For edifice this project in Python who tin can use the Pygame Python library that is loaded with all computer graphics and sounds.
Sample Code:
""" Tic Tac Toe
----------------------------------------
"""
import random
import sys
board=[i for i in range(0,9)]
histrion, calculator = '',''
// Corners, Heart and Others, respectively
moves=((1,vii,iii,nine),(5,),(two,four,6,8))
// Winner combinations
winners=((0,ane,2),(3,4,5),(6,7,viii),(0,3,6),(one,4,vii),(2,5,8),(0,4,8),(two,4,half dozen))
// Table
tab=range(1,10)
def print_board():
x=1
for i in lath:
end = ' | '
if x%3 == 0:
finish = ' \n'
if i != 1: terminate+='---------\n';
char=' '
if i in ('X','O'): char=i;
x+=one
print(char,terminate=finish)
def select_char():
chars=('X','O')
if random.randint(0,1) == 0:
render chars[::-1]
return chars
def can_move(brd, player, move):
if move in tab and brd[move-1] == movement-1:
return Truthful
render False
def can_win(brd, player, move):
places=[]
x=0
for i in brd:
if i == player: places.suspend(x);
x+=one
win=True
for tup in winners:
win=True
for ix in tup:
if brd[ix] != player:
win=False
pause
if win == True:
intermission
render win
def make_move(brd, thespian, move, undo=Imitation):
if can_move(brd, player, movement):
brd[movement-i] = player
win=can_win(brd, player, motion)
if disengage:
brd[move-1] = move-1
return (True, win)
return (False, Imitation)
// AI goes here
def computer_move():
movement=-ane
// If I tin can win, others do not matter.
for i in range(1,x):
if make_move(board, computer, i, Truthful)[1]:
move=i
break
if motility == -one:
// If thespian can win, block him.
for i in range(one,10):
if make_move(board, player, i, True)[one]:
motility=i
break
if move == -i:
// Otherwise, try to take 1 of desired places.
for tup in moves:
for mv in tup:
if movement == -ane and can_move(lath, computer, mv):
motility=mv
break
return make_move(board, computer, move)
def space_exist():
return board.count('Ten') + lath.count('O') != 9
histrion, computer = select_char()
impress('Player is [%south] and computer is [%s]' % (player, figurer))
result='%%% Deuce ! %%%'
while space_exist():
print_board()
print('#Make your movement ! [1-9] : ', end='')
move = int(input())
moved, won = make_move(board, histrion, motility)
if not moved:
print(' >> Invalid number ! Try again !')
go along
//
if won:
result='*** Congratulations ! You won ! ***'
break
elif computer_move()[1]:
event='=== You lose ! =='
break;
print_board()
impress(issue)
4. Directory Tree Generator
This project is useful for visualizing the relationship betwixt files and directories and making their positioning easy to comprehend. Python OS library can be used to list the files and directories within a specific directory. The first-class frameworks of this project are Docopt and Argparse.
Sample Code:
""" Directory Tree Generator
----------------------------------------
"""
import argparse
import os
from walkdir import filtered_walk
parser = argparse.ArgumentParser(description='Print the directory-tree code for the LaTeX dirtree package.')
parser.add_argument(dest='path', blazon=str, help="Root directory of the tree")
parser.add_argument('-d', '--maxDepth', dest='maxDepth', type=int, help="Max depth for tree expansion")
parser.add_argument('-H', '--includeHidden', dest='includeHidden', action='store_true', assist='Include hidden files')
parser.add_argument('-S', '--includeSystem', dest='includeSystem', activity='store_true', assist='Include system files')
system_file_names = [".DS_Store"]
// Delete trailing / in rootDir which can pb to errors
def delete_trailing_slash(path_name):
while path_name.endswith('/'):
path_name = path_name[:-1]
return path_name
// Count how many levels deep is the directory with respect to dirRoot
def get_relative_depth(dir_path, level_offset):
return dir_path.count(os.path.sep) - level_offset
// Escape illegal symbols for LaTeX
def escape_illegal(proper noun):
illegal_char_array = ['\\', '&', '%', '$', '#', '_', '{', '}', '~', '^']
for char in illegal_char_array:
name = name.replace(char, "\\" + char)
return name
rootDir = delete_trailing_slash(parser.parse_args().path)
includeHidden = parser.parse_args().includeHidden
includeSystem = parser.parse_args().includeSystem
maxDepth = parser.parse_args().maxDepth
// if the directory exists
if bone.path.isdir(rootDir) and os.path.exists(rootDir):
indentChar = " "
// Depth of the root (i.e. number of "/")
levelOffset = rootDir.count(os.path.sep) - 1
// Create filter
excluded_filter = []
if not includeHidden:
excluded_filter.append(".*")
if not includeSystem:
excluded_filter += system_file_names
print ("\dirtree{%")
for dirName, subdirList, fileList in sorted(filtered_walk(rootDir, depth=maxDepth, excluded_dirs=excluded_filter,
excluded_files=excluded_filter)):
level = get_relative_depth(dirName, levelOffset)
baseName = os.path.basename(dirName)
if level == ane: // for the first level only print the whole path
print(indentChar + "." + str(level) + " {" + escape_illegal(dirName) + "} .")
else:
print(indentChar * level + "." + str(level) + " {" + escape_illegal((os.path.basename(dirName))) + "} .")
level += i
for fileName in sorted(fileList):
print(indentChar * level + "." + str(level) + " {" + escape_illegal(fileName) + "} .")
print ("}")
else:
print ("Error: root directory not establish")
v. Currency Converter
This is a straightforward project with a simple GUI. The name quite plain describes the role of the project is to convert currencies from one unit into another. For instance, converting Indian rupee to USD or euro. Tkinter, the standard Python interface can exist used to design and develop this application.
Sample Code:
""" Currency Converter
----------------------------------------
"""
import urllib.asking
import json
def currency_converter(currency_from, currency_to, currency_input):
yql_base_url = "https://query.yahooapis.com/v1/public/yql"
yql_query = 'select%xx*%20from%20yahoo.finance.xchange%20where%20pair' \
'%20in%20("'+currency_from+currency_to+'")'
yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
attempt:
yql_response = urllib.request.urlopen(yql_query_url)
try:
json_string = str(yql_response.read())
json_string = json_string[two:
json_string = json_string[:-one]
print(json_string)
yql_json = json.loads(json_string)
last_rate = yql_json['query']['results']['rate']['Rate']
currency_output = currency_input * float(last_rate)
return currency_output
except (ValueError, KeyError, TypeError):
print(yql_query_url)
return "JSON format error"
except IOError as east:
print(str(due east))
currency_input = 1
// currency codes : http://en.wikipedia.org/wiki/ISO_4217
currency_from = "USD"
currency_to = "Endeavour"
rate = currency_converter(currency_from, currency_to, currency_input)
print(rate)
You can too refer here.
Advanced Level Projection Ideas
1. Content Aggregator
Surfing through unlike websites and articles in search of good and authentic content is a time-consuming procedure. This Python project tin can help you save fourth dimension looking for content. A content aggregator searches popular websites in search for relevant content and then complies with all the content and provides the user with unbiased content.
Sample Lawmaking:
""" Content Aggregator
----------------------------------------
"""
import urllib, os, requests, datetime, subprocess
// reddit imports
import praw, pprint
// pip install feedparser
import feedparser
// stockexchange
from nsetools import Nse
// Place your CLIENT_ID & CLIENT_SECRET below
reddit = praw.Reddit(client_id='XXXXXXX',
client_secret='XXXXXXXXXXX',
grant_type_access='client_credentials',
user_agent='script/1.0')
// class Reddit:
// def TopNews(cocky):
// Add your favorite NEWS subreddits in the argument equally many as you'd similar.
// for submission in reddit.subreddit('News+WorldNews+UpliftingNews+').top(limit=x):
// top_news = reddit.domain(submission).top('month')
// impress(top_news)
"""
Each class contains functions which further calls
APIs from the neccesary packages and the residuum is
self explanatory I suppose
"""
form News:
def Indian_News(self):
newsfeed = feedparser.parse(
"http://feeds.feedburner.com/ndtvnews-bharat-news"
)
print("Today's News: ")
for i in range(0, xx):
entry = newsfeed.entries[i]
print(entry.title)
print(entry.summary)
print("------News Link--------")
print(entry.link)
print("###########################################")
print('-------------------------------------------------------------------------------------------------------')
class Medium:
// https://github.com/thepracticaldev/dev.to/issues/28#issuecomment-325544385
def medium_programming(self):
feed = feedparser.parse(
"https://medium.com/feed/tag/programming"
)
print("Programming Today: ")
for i in range(x):
entry = feed.entries[i]
impress(entry.title)
print("URL: " + entry.link)
impress("###########################################")
print('-------------------------------------------------------------------------------------------------------')
def medium_python(self):
feed_python = feedparser.parse(
"https://medium.com/feed/tag/python"
)
print("Python Today: ")
for i in range(ten):
entry = feed_python.entries[i]
print(entry.championship)
print("URL: " + entry.link)
impress("###########################################")
print('-------------------------------------------------------------------------------------------------------')
def medium_developer(self):
feed_developer = feedparser.parse(
"https://medium.com/feed/tag/developer"
)
print("Developer News Today: ")
for i in range(5):
entry = feed_developer.entries[i]
print(entry.title)
print("URL: " + entry.link)
print("###########################################")
print('-------------------------------------------------------------------------------------------------------')
class StockExchange:
def nse_stock(cocky):
nse = Nse()
impress("TOP GAINERS OF YESTERDAY")
pprint.pprint(nse.get_top_gainers())
print("###########################################")
impress("TOP LOSERS OF YESTERDAY")
pprint.pprint(nse.get_top_losers())
print("###########################################")
print('-------------------------------------------------------------------------------------------------------')
// objects inititalization
// reddit_object = Reddit()
News_object = News()
Medium_object = Medium()
StockExchange_object = StockExchange()
if __name__ == "__main__":
// Functions telephone call of each class
// reddit_object.TopNews()
News_object.Indian_News()
Medium_object.medium_python()
Medium_object.medium_programming()
Medium_object.medium_developer()
StockExchange_object.nse_stock()
2. Plagiarism Checker
With content creation and blogging one of the practiced businesses in the market everyone wants to try their easily on this but some lack sufficient funds to give their articles a free plagiarism check equally mostly plagiarism checkers do not come up for free. Building a Python plagiarism checker could be congenital here using a natural language processing library along with the search API to search the get-go few pages of Google and detect plagiarism if whatsoever.
Sample Code:
""" Plagiarism Checker
----------------------------------------
"""
import click
from .matcher import Text, ExtendedMatch, Matcher
import os
import glob
import csv
import logging
import itertools
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def getFiles(path):
"""
Determines whether a path is a file or directory.
If it's a directory, it gets a list of all the text files
in that directory, recursively. If non, it gets the file.
"""
if bone.path.isfile(path):
return [path]
elif os.path.isdir(path):
// Get list of all files in dir, recursively.
return glob.glob(path + "/**/*.txt", recursive=True)
else:
raise click.ClickException("The path %southward doesn't announced to be a file or directory" % path)
def checkLog(logfile, textpair):
"""
Checks the log file to make sure nosotros haven't already done a particular analysis.
Returns True if the pair is in the log already.
"""
pairs = []
logging.debug('Looking in the log for textpair:' % textpair)
if not os.path.isfile(logfile):
logging.debug('No log file found.')
render None
with open(logfile, newline='') as f:
reader = csv.reader(f)
for row in reader:
pairs.append([row[0], row[1]])
// logging.debug('Pairs already in log: %s' % pairs)
return textpair in pairs
def createLog(logfile, columnLabels):
"""
Creates a log file and sets upward headers so that information technology tin be easily read
as a CSV afterward.
"""
header = ','.join(columnLabels) + '\n'
with open up(logfile, 'w') equally f:
f.write(header)
f.close
@click.command()
@click.argument('text1')
@click.argument('text2')
@click.selection('-t', '--threshold', type=int, default=three, \
help='The shortest length of match to include in the list of initial matches.')
@click.option('-c', '--cutoff', type=int, default=5, \
help='The shortest length of match to include in the final list of extended matches.')
@click.pick('-n', '--ngrams', type=int, default=3, \
help='The ngram north-value to match against.')
@click.pick('-l', '--logfile', default='log.txt', assist='The proper name of the log file to write to.'
@click.option('--stops', is_flag=True, assist='Include stopwords in matching.', default=False)
@click.choice('--verbose', is_flag=Truthful, help='Enable verbose way, giving more than data.')
def cli(text1, text2, threshold, cutoff, ngrams, logfile, verbose, stops):
""" This plan finds like text in two text files. """
//Determine whether the given path is a file or directory.
texts1 = getFiles(text1)
texts2 = getFiles(text2)
if verbose:
logging.basicConfig(level=logging.DEBUG)
if stops:
logging.debug('Including stopwords in tokenizing.')
logging.debug('Comparing this/these text(southward): %s' % str(texts1))
logging.debug('with this/these text(due south): %s' % str(texts2))
pairs = list(itertools.production(texts1, texts2))
numPairs = len(pairs)
logging.debug('Comparing %s pairs.' % numPairs)
// logging.debug('Listing of pairs to compare: %southward' % pairs)
logging.debug('Loading files into memory.')
texts = {}
prevTextObjs = {}
for filename in texts1+texts2:
with open up(filename, errors="ignore") as f:
text = f.read()
if filename not in texts:
texts[filename] = text
logging.debug('Loading complete.')
for index, pair in enumerate(pairs):
timeStart = os.times().elapsed
logging.debug('At present comparison pair %s of %south.' % (index+1, numPairs))
logging.debug('Comparing %s with %south.' % (pair[0], pair[i]))
// Make sure we haven't already done this pair.
inLog = checkLog(logfile, [pair[0], pair[1]])
if inLog is None:
// This ways that there isn't a log file. Permit's set one upward.
// Gear up columns and their labels.
columnLabels = ['Text A', 'Text B', 'Threshold', 'Cutoff', 'N-Grams', 'Num Matches', 'Text A Length', 'Text B Length', 'Locations in A', 'Locations in B']
logging.debug('No log file found. Setting one upward.')
createLog(logfile, columnLabels)
if inLog:
logging.debug('This pair is already in the log. Skipping.')
proceed
logging.debug('Processing texts.')
filenameA, filenameB = pair[0], pair[i]
textA, textB = texts[filenameA], texts[filenameB]
// Put this in a lexicon so we don't have to process a file twice.
for filename in [filenameA, filenameB]:
if filename non in prevTextObjs:
logging.debug('Processing text: %s' % filename)
prevTextObjs[filename] = Text(texts[filename], filename)
// Just more convenient naming.
textObjA = prevTextObjs[filenameA]
textObjB = prevTextObjs[filenameB]
// Reset the table of previous text objects, and so nosotros don't overload memory.
// This means nosotros'll only call back the previous two texts.
prevTextObjs =
// Practise the matching.
myMatch = Matcher(textObjA, textObjB, threshold=threshold, cutoff=cutoff, ngramSize=ngrams, removeStopwords=stops)
myMatch.match()
timeEnd = os.times().elapsed
timeElapsed = timeEnd-timeStart
logging.debug('Matching completed in %s seconds.' % timeElapsed)
// Write to the log, simply simply if a friction match is plant.
if myMatch.numMatches > 0:
logItems = [pair[0], pair[1], threshold, cutoff, ngrams, myMatch.numMatches, myMatch.textA.length, myMatch.textB.length, str(myMatch.locationsA), str(myMatch.locationsB)]
logging.debug('Logging items: %s' % str(logItems))
line = ','.join(['"%s"' % item for item in logItems]) + '\n'
f = open(logfile, 'a')
f.write(line)
f.shut()
if __name__ == '__main__':
cli()
iii. Web Crawler
Web crawler projection is an automated script designed to surf the internet and store the content of certain webpages. A web crawler is especially useful to discover up-to-date information using multi-thread concepts in its plan. A crawler bot is built using Python's request module or Scrapy, a Python's open-source web crawling framework explicitly designed for web scraping and extracting data by using APIs. Here you lot tin can meet this python projection source code.
Sample Code:
""" Spider web Crawler
----------------------------------------
"""
import re
import sys
import time
import math
import urllib2
import urlparse
import optparse
import hashli
from cgi import escape
from traceback import format_exc
from Queue import Queue, Empty as QueueEmpty
from bs4 import BeautifulSoup
class Link (object):
def __init__(cocky, src, dst, link_type):
cocky.src = src
self.dst = dst
cocky.link_type = link_type
def __hash__(self):
return hash((self.src, self.dst, self.link_type))
def __eq__(cocky, other):
return (self.src == other.src and
self.dst == other.dst and
self.link_type == other.link_type)
def __str__(self):
return self.src + " -> " + self.dst
grade Crawler(object):
def __init__(cocky, root, depth_limit, confine=None, exclude=[], locked=Truthful, filter_seen=True):
self.root = root
self.host = urlparse.urlparse(root)[ane]
## Data for filters:
cocky.depth_limit = depth_limit # Max depth (number of hops from root)
self.locked = locked # Limit search to a single host?
self.confine_prefix=confine # Limit search to this prefix
self.exclude_prefixes=exclude; # URL prefixes NOT to visit
cocky.urls_seen = set() # Used to avoid putting duplicates in queue
cocky.urls_remembered = ready() # For reporting to user
self.visited_links= ready() # Used to avoid re-processing a page
cocky.links_remembered = set() # For reporting to user
cocky.num_links = 0 # Links establish (and non excluded by filters)
cocky.num_followed = 0 # Links followed.
# Pre-visit filters: Simply visit a URL if it passes these tests
cocky.pre_visit_filters=[self._prefix_ok,
self._exclude_ok,
self._not_visited,
cocky._same_host]
// Out-url filters: When examining a visited page, only process
// links where the target matches these filters.
if filter_seen:
cocky.out_url_filters=[cocky._prefix_ok,
cocky._same_host]
else:
cocky.out_url_filters=[]
def _pre_visit_url_condense(self, url):
""" Reduce (condense) URLs into some canonical class before
visiting. All occurrences of equivalent URLs are treated every bit
identical.
All this does is strip the \"fragment\" component from URLs,
so that http://foo.com/blah.html\#baz becomes
http://foo.com/blah.html """
base of operations, frag = urlparse.urldefrag(url)
return base
// URL Filtering functions. These all utilize information from the
// country of the Crawler to evaluate whether a given URL should be
// used in some context. Render value of Truthful indicates that the
// URL should be used.
def _prefix_ok(self, url):
"""Pass if the URL has the correct prefix, or none is specified"""
return (self.confine_prefix is None or
url.startswith(self.confine_prefix))
def _exclude_ok(self, url):
"""Laissez passer if the URL does not friction match any exclude patterns"""
prefixes_ok = [ non url.startswith(p) for p in self.exclude_prefixes]
return all(prefixes_ok)
def _not_visited(self, url):
"""Pass if the URL has not already been visited"""
return (url not in self.visited_links)
def _same_host(self, url):
"""Pass if the URL is on the same host as the root URL"""
try:
host = urlparse.urlparse(url)[1]
return re.match(".*%s" % self.host, host)
except Exception, eastward:
print >> sys.stderr, "Error: Tin can't process url '%s' (%s)" % (url, e)
render False
def crawl(self):
""" Main office in the crawling procedure. Core algorithm is:
q <- starting page
while q not empty:
url <- q.become()
if url is new and suitable:
page <- fetch(url)
q.put(urls constitute in page)
else:
nil
new and suitable means that we don't re-visit URLs nosotros've seen
already fetched, and user-supplied criteria like maximum
search depth are checked. """
q = Queue()
q.put((cocky.root, 0))
while not q.empty():
this_url, depth = q.become()
#Non-URL-specific filter: Discard anything over depth limit
if depth > self.depth_limit:
continue
//Apply URL-based filters.
do_not_follow = [f for f in cocky.pre_visit_filters if not f(this_url)]
#Special-instance depth 0 (starting URL)
if depth == 0 and [] != do_not_follow:
impress >> sys.stderr, "Whoops! Starting URL %s rejected by the post-obit filters:", do_not_follow
//If no filters failed (that is, all passed), process URL
if [] == do_not_follow:
try:
cocky.visited_links.add together(this_url)
cocky.num_followed += 1
page = Fetcher(this_url)
page.fetch()
for link_url in [self._pre_visit_url_condense(l) for 50 in page.out_links()]:
if link_url non in self.urls_seen:
q.put((link_url, depth+ane))
self.urls_seen.add together(link_url)
do_not_remember = [f for f in cocky.out_url_filters if not f(link_url)]
if [] == do_not_remember:
self.num_links += 1
cocky.urls_remembered.add(link_url)
link = Link(this_url, link_url, "href")
if link not in self.links_remembered:
self.links_remembered.add(link)
except Exception, e:
print >>sys.stderr, "ERROR: Tin't procedure url '%s' (%s)" % (this_url, due east)
#impress format_exc()
class OpaqueDataException (Exception):
def __init__(self, message, mimetype, url):
Exception.__init__(self, message)
self.mimetype=mimetype
self.url=url
course Fetcher(object):
"""The name Fetcher is a slight misnomer: This class retrieves and interprets spider web pages."""
def __init__(cocky, url):
self.url = url
self.out_urls = []
def __getitem__(self, x):
render self.out_urls[x]
def out_links(self):
return self.out_urls
//def _addHeaders(self, request):
// request.add_header("User-Agent", Amanuensis)
def _open(self):
url = cocky.url
endeavor:
request = urllib2.Asking(url)
handle = urllib2.build_opener()
except IOError:
return None
return (request, handle)
def fetch(self):
request, handle = cocky._open()
#self._addHeaders(request)
if handle:
attempt:
data=handle.open up(request)
mime_type=information.info().gettype()
url=data.geturl();
if mime_type != "text/html":
raise OpaqueDataException("Non interested in files of type %s" % mime_type,
mime_type, url)
content = unicode(data.read(), "utf-8",
errors="supplant")
soup = BeautifulSoup(content)
tags = soup('a')
except urllib2.HTTPError, fault:
if error.code == 404:
print >> sys.stderr, "ERROR: %s -> %southward" % (error, error.url)
else:
impress >> sys.stderr, "Error: %south" % mistake
tags = []
except urllib2.URLError, fault:
print >> sys.stderr, "ERROR: %s" % fault
tags = []
except OpaqueDataException, fault:
impress >>sys.stderr, "Skipping %s, has type %s" % (error.url, fault.mimetype)
tags = []
for tag in tags:
href = tag.get("href")
if href is not None:
url = urlparse.urljoin(cocky.url, escape(href))
if url not in self:
self.out_urls.append(url)
def getLinks(url):
page = Fetcher(url)
folio.fetch()
"""for i, url in enumerate(folio):
print "%d. %south" % (i, url) """
j = i
for i, url in enumerate(page):
if url.find("http")>=0:
impress "%d. %south" % (j, url)
j = j + i
def parse_options():
"""parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
"""
parser = optparse.OptionParser()
parser.add_option("-q", "--repose",
action="store_true", default=False, dest="repose",
assistance="Enable tranquility style")
parser.add_option("-fifty", "--links",
action="store_true", default=False, dest="links",
help="Get links for specified url only")
parser.add_option("-d", "--depth",
activeness="store", type="int", default=30, dest="depth_limit",
assistance="Maximum depth to traverse")
parser.add_option("-c", "--confine",
action="store", type="string", dest="confine",
help="Confine crawl to specified prefix")
parser.add_option("-x", "--exclude", action="suspend", blazon="string",
dest="exclude", default=[], help="Exclude URLs past prefix")
parser.add_option("-L", "--show-links", activity="store_true", default=False,
dest="out_links", help="Output links institute")
parser.add_option("-u", "--evidence-urls", action="store_true", default=Imitation,
dest="out_urls", help="Output URLs found")
parser.add_option("-D", "--dot", action="store_true", default=Faux,
dest="out_dot", help="Output Graphviz dot file")
opts, args = parser.parse_args()
if len(args) < 1:
parser.print_help(sys.stderr)
raise SystemExit, one
if opts.out_links and opts.out_urls:
parser.print_help(sys.stderr)
parser.error("options -Fifty and -u are mutually exclusive")
return opts, args
class DotWriter:
""" Formats a collection of Link objects as a Graphviz (Dot)
graph. By and large, this ways creating a node for each URL with a
name which Graphviz will accept, and declaring links betwixt those
nodes."""
def __init__ (cocky):
self.node_alias = {}
def _safe_alias(cocky, url, silent=False):
"""Translate URLs into unique strings guaranteed to exist prophylactic as
node names in the Graphviz linguistic communication. Currently, that'south based
on the md5 assimilate, in hexadecimal."""
if url in self.node_alias:
return self.node_alias[url]
else:
k = hashlib.md5()
g.update(url)
name = "Due north"+k.hexdigest()
self.node_alias[url]=proper name
if not silent:
impress "\t%s [label=\"%s\"];" % (name, url)
render name
def asDot(self, links):
""" Render a drove of Link objects equally a Dot graph"""
print "digraph Crawl {"
print "\t border [K=0.two, len=0.1];"
for fifty in links:
print "\t" + cocky._safe_alias(50.src) + " -> " + self._safe_alias(l.dst) + ";"
print "}"
def main():
opts, args = parse_options()
url = args[0]
if opts.links:
getLinks(url)
heighten SystemExit, 0
depth_limit = opts.depth_limit
confine_prefix=opts.confine
exclude=opts.exclude
sTime = time.time()
impress >> sys.stderr, "Crawling %south (Max Depth: %d)" % (url, depth_limit)
crawler = Crawler(url, depth_limit, confine_prefix, exclude)
crawler.clamber()
if opts.out_urls:
impress "\north".bring together(crawler.urls_seen)
if opts.out_links:
impress "\n".join([str(l) for fifty in crawler.links_remembered])
if opts.out_dot:
d = DotWriter()
d.asDot(crawler.links_remembered)
eTime = time.time()
tTime = eTime - sTime
print >> sys.stderr, "Found: %d" % crawler.num_links
print >> sys.stderr, "Followed: %d" % crawler.num_followed
print >> sys.stderr, "Stats: (%d/s after %0.2fs)" % (
int(math.ceil(float(crawler.num_links) / tTime)), tTime)
if __name__ == "__main__":
main()
4. Music Thespian
How about building your personal music player? This really sounds heady to me. Create and build not just whatsoever other music app simply also aa app which searches through files and explores your program directories in search of music. Build an interactive interface to be used by other users every bit well.
Consider adding features like browsing through tracks, volume control, song/creative person/ anthology/ picture display, database direction, algorithm structure, and data processing to develop a fully-featured interactive app.
Sample Code:
""" Music Player
----------------------------------------
"""
import bone
import threading
import time
import tkinter.messagebox
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from ttkthemes import themed_tk as tk
from mutagen.mp3 import MP3
from pygame import mixer
root = tk.ThemedTk()
root.get_themes() // Returns a listing of all themes that can be set
root.set_theme("radiance") // Sets an available theme
// Fonts - Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys,
// MS Sans Serif, MS Serif, Symbol, Organization, Times New Roman (Times), and Verdana
//
// Styles - normal, bold, roman, italic, underline, and overstrike.
statusbar = ttk.Label(root, text="Welcome to Melody", relief=SUNKEN, anchor=W, font='Times x italic')
statusbar.pack(side=BOTTOM, fill=X)
// Create the menubar
menubar = Menu(root)
root.config(menu=menubar)
// Create the submenu
subMenu = Card(menubar, tearoff=0)
playlist = []
// playlist - contains the total path + filename
// playlistbox - contains only the filename
// Fullpath + filename is required to play the music inside play_music load office
def browse_file():
global filename_path
filename_path = filedialog.askopenfilename()
add_to_playlist(filename_path)
mixer.music.queue(filename_path)
def add_to_playlist(filename):
filename = os.path.basename(filename)
alphabetize = 0
playlistbox.insert(index, filename)
playlist.insert(index, filename_path)
index += 1
menubar.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Open up", command=browse_file)
subMenu.add_command(label="Exit", command=root.destroy)
def about_us():
tkinter.messagebox.showinfo('Most Melody', 'This is a music player build using Python Tkinter by @attreyabhatt')
subMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(characterization="Help", menu=subMenu)
subMenu.add_command(characterization="About Us", command=about_us)
mixer.init() // initializing the mixer
root.championship("Tune")
root.iconbitmap(r'images/melody.ico')
// Root Window - StatusBar, LeftFrame, RightFrame
// LeftFrame - The listbox (playlist)
// RightFrame - TopFrame,MiddleFrame and the BottomFrame
leftframe = Frame(root)
leftframe.pack(side=LEFT, padx=30, pady=30)
playlistbox = Listbox(leftframe)
playlistbox.pack()
addBtn = ttk.Button(leftframe, text="+ Add", command=browse_file)
addBtn.pack(side=LEFT)
def del_song():
selected_song = playlistbox.curselection()
selected_song = int(selected_song[0])
playlistbox.delete(selected_song)
playlist.popular(selected_song)
delBtn = ttk.Button(leftframe, text="- Del", command=del_song)
delBtn.pack(side=LEFT)
rightframe = Frame(root)
rightframe.pack(pady=30)
topframe = Frame(rightframe)
topframe.pack()
lengthlabel = ttk.Label(topframe, text='Total Length : --:--')
lengthlabel.pack(pady=5)
currenttimelabel = ttk.Label(topframe, text='Current Time : --:--', relief=GROOVE)
currenttimelabel.pack()
def show_details(play_song):
file_data = bone.path.splitext(play_song)
if file_data[ane] == '.mp3':
audio = MP3(play_song)
total_length = audio.info.length
else:
a = mixer.Sound(play_song)
total_length = a.get_length()
// div - total_length/60, mod - total_length % lx
mins, secs = divmod(total_length, threescore)
mins = circular(mins)
secs = round(secs)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
lengthlabel['text'] = "Total Length" + ' - ' + timeformat
t1 = threading.Thread(target=start_count, args=(total_length,))
t1.start()
def start_count(t):
global paused
// mixer.music.get_busy(): - Returns Simulated when we press the stop button (music stop playing)
// Continue - Ignores all of the statements below it. Nosotros check if music is paused or not.
current_time = 0
while current_time <= t and mixer.music.get_busy():
if paused:
continue
else:
mins, secs = divmod(current_time, sixty)
mins = round(mins)
secs = round(secs)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
currenttimelabel['text'] = "Current Time" + ' - ' + timeformat
time.slumber(one)
current_time += 1
def play_music():
global paused
if paused:
mixer.music.unpause()
statusbar['text'] = "Music Resumed"
paused = FALSE
else:
try:
stop_music()
fourth dimension.sleep(i)
selected_song = playlistbox.curselection()
selected_song = int(selected_song[0])
play_it = playlist[selected_song]
mixer.music.load(play_it)
mixer.music.play()
statusbar['text'] = "Playing music" + ' - ' + bone.path.basename(play_it)
show_details(play_it)
except:
tkinter.messagebox.showerror('File non institute', 'Tune could non discover the file. Please cheque again.')
def stop_music():
mixer.music.terminate()
statusbar['text'] = "Music Stopped"
paused = FALSE
def pause_music():
global paused
paused = Truthful
mixer.music.pause()
statusbar['text'] = "Music Paused"
def rewind_music():
play_music()
statusbar['text'] = "Music Rewinded"
def set_vol(val):
volume = float(val) / 100
mixer.music.set_volume(volume)
// set_volume of mixer takes value only from 0 to 1. Example - 0, 0.i,0.55,0.54.0.99,1
muted = Simulated
def mute_music():
global muted
if muted: // Unmute the music
mixer.music.set_volume(0.vii)
volumeBtn.configure(image=volumePhoto)
scale.set(70)
muted = FALSE
else: // mute the music
mixer.music.set_volume(0)
volumeBtn.configure(image=mutePhoto)
scale.prepare(0)
muted = TRUE
middleframe = Frame(rightframe)
middleframe.pack(pady=30, padx=xxx)
playPhoto = PhotoImage(file='images/play.png')
playBtn = ttk.Button(middleframe, image=playPhoto, command=play_music)
playBtn.grid(row=0, column=0, padx=10)
stopPhoto = PhotoImage(file='images/stop.png')
stopBtn = ttk.Button(middleframe, epitome=stopPhoto, command=stop_music)
stopBtn.grid(row=0, column=ane, padx=x)
pausePhoto = PhotoImage(file='images/break.png')
pauseBtn = ttk.Button(middleframe, prototype=pausePhoto, control=pause_music)
pauseBtn.grid(row=0, column=two, padx=x)
// Lesser Frame for volume, rewind, mute etc.
bottomframe = Frame(rightframe)
bottomframe.pack()
rewindPhoto = PhotoImage(file='images/rewind.png')
rewindBtn = ttk.Push button(bottomframe, image=rewindPhoto, command=rewind_music)
rewindBtn.filigree(row=0, column=0)
mutePhoto = PhotoImage(file='images/mute.png')
volumePhoto = PhotoImage(file='images/volume.png')
volumeBtn = ttk.Button(bottomframe, prototype=volumePhoto, command=mute_music)
volumeBtn.grid(row=0, column=one)
scale = ttk.Scale(bottomframe, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
scale.set up(lxx) # implement the default value of calibration when music actor starts
mixer.music.set_volume(0.7)
calibration.filigree(row=0, cavalcade=2, pady=fifteen, padx=30)
def on_closing():
stop_music()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
5. Instagram Photo Downloader
This application comes handy when you wish to delete an Instagram account but wish to keep your drove of images. As this app uses user credentials to open their account and then look for their friend's ID and download their photos.
Sample Code:
""" Instagram Photo Downloader
----------------------------------------
"""
from sys import argv
import urllib
from bs4 import BeautifulSoup
import datetime
def ShowHelp():
impress 'Insta Image Downloader'
print ''
impress 'Usage:'
print 'insta.py [OPTION] [URL]'
print ''
print 'Options:'
print '-u [Instagram URL]\tDownload single photo from Instagram URL'
print '-f [File path]\t\tDownload Instagram photo(s) using file listing'
impress '-h, --help\t\tShow this assist message'
print ''
print 'Example:'
impress 'python insta.py -u https://instagram.com/p/xxxxx'
print 'python insta.py -f /home/username/filelist.txt'
print ''
exit()
def DownloadSingleFile(fileURL):
print 'Downloading image...'
f = urllib.urlopen(fileURL)
htmlSource = f.read()
soup = BeautifulSoup(htmlSource,'html.parser')
metaTag = soup.find_all('meta', {'property':'og:epitome'})
imgURL = metaTag[0]['content']
fileName = datetime.datetime.at present().strftime("%Y-%m-%d_%H:%M:%S") + '.jpg'
urllib.urlretrieve(imgURL, fileName)
print 'Done. Paradigm saved to disk as ' + fileName
if __name__ == '__main__':
if len(argv) == 1:
ShowHelp()
if argv[1] in ('-h', '--help'):
ShowHelp()
elif argv[1] == '-u':
instagramURL = argv[2]
DownloadSingleFile(instagramURL)
elif argv[1] == '-f':
filePath = argv[2]
f = open up(filePath)
line = f.readline()
while line:
instagramURL = line.rstrip('\due north')
DownloadSingleFile(instagramURL)
line = f.readline()
f.close()
Conclusion
This brings us to the fun-filled Python project ideas. I promise you too found it exciting to read as much as I did writing it. And so put all your theoretical learning together and implement it practically to increase your Python coding skills. Creating projects could exist a plus while you await for jobs, y'all may as well consider reading Python Interview Questions for your competitive preparation.
Want to master Python programming? Python Mega Form: Build 10 Real Globe Applications is a highly rated and recommended class for learning Python.
Which project do you prefer to build? Or have y'all already built some of them? What's your feedback on those projects? Share with us nosotros would dear to hear from you and also motivate other Python developers.
People are also reading:
- Best Python Courses
- All-time Python Certifications
- Best Python IDE
- Best Python Compilers
- All-time Python Interpreters
- Best way to learn python
- How to Run a Python Script?
- What is PyCharm?
- Python for Data Scientific discipline
- Top Python Libraries
DOWNLOAD HERE
Posted by: samanthafection61.blogspot.com