5 Quick Python Projects
Tags: python, programming, coding
Published: 2021-05-29 17:48:50

<p>In this blog, we&#39;ll be building five different Python projects. These projects will be a little bit above the beginner&#39;s level, so we can consider them as <strong>Intermediate Python Projects</strong>. So, we are going to build the below mentioned five projects :</p>

<ol>
	<li>Web Scraping Program</li>
	<li>Renaming Bulk Files</li>
	<li>Getting Weather Information</li>
	<li>Password Generator</li>
	<li>QR Codes with Python</li>
</ol>

<p>Having that said, let&#39;s jump to building these cool projects.</p>

<p>&nbsp;</p>

<h1><strong>Web Scraping Program</strong></h1>

<p>In this project, we&#39;ll be using Web Scraping to <strong>get the image link of the profile image of a particular Github user</strong>. So, what our program is going to do, it&#39;s going to ask for a Github username and then it will return the image link of that account.</p>

<p><img alt="" src="https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/screenshot-1_lxtcma" /></p>

<p><br />
Before we start we need to install two external Python libraries - <strong>requests </strong>and <strong>bs4 </strong>:&nbsp;</p>

<pre>
<code class="language-bash">pip install requests bs4</code></pre>

<p>The above command will install these two libraries and now we are ready for coding.</p>

<p>So, the first thing we need to do is to import these ibraries in our code :</p>

<pre>
<code class="language-python">import requests
from bs4 import BeautifulSoup as bs</code></pre>

<p>Now, let&#39;s understand how we are going to proceed. First, we are going to fetch the user&#39;s profile on Github using requests and pass all the HTML content of the page to the BeautifulSoup to parse using an HTML parser. Now, we need to understand one thing. To fetch the user&#39;s image, we need to visit its profile and inspect the HTML content first in order to visualize how we are going to extract the image. SO, after inspecting, we have this HTML content that is used for the profile image (as of now):</p>

<pre>
<code class="language-html">&lt;img style="height:auto;" alt="" width="260" height="260" class="avatar avatar-user width-full border color-bg-primary" src="https://avatars.githubusercontent.com/u/47353498?v=4"&gt;</code></pre>

<p>In this HTML content, we need to find a unique attribute using which we can fetch the <strong>src</strong> of the <strong>img </strong>tag. We can use the class&nbsp;<strong>avatar avatar-user&nbsp;</strong>for this, and this way we can get the image link. Now let&#39;s jump to the code :&nbsp;</p>

<pre>
<code class="language-python">def get_profile_image(username) -&gt; str:
    url = f"https://github.com/{username}/"
    res = requests.get(url)
    soup = bs(res.content, 'html.parser')
    profile_image = soup.select('img.avatar.avatar-user')[0]['src']
    return profile_image</code></pre>

<p>In the above code, we are first making a GET request on the user&#39;s profile and then using the select method in soup to get the image tag with class avatar <strong>AND </strong>avatar-user. This will return us a list of all the image tags with this class. We need to get the first element of the list and get its src.</p>

<p>So, our entire code is now :&nbsp;</p>

<pre>
<code class="language-python">import requests
from bs4 import BeautifulSoup as bs

def get_profile_image(username) -&gt; str:
    url = f"https://github.com/{username}/"
    res = requests.get(url)
    soup = bs(res.content, 'html.parser')
    profile_image = soup.select('img.avatar.avatar-user')[0]['src']
    return profile_image


if __name__ == "__main__":
    github_username = input("Enter Github Username : ")
    print(get_profile_image(github_username))</code></pre>

<p>&nbsp;</p>

<div style="background:#eeeeee; border:1px solid #cccccc; padding:5px 10px">
<p><strong>Note </strong>: This code cannot be used later since the HTML content may change in future.</p>
</div>

<p>&nbsp;</p>

<h1><strong>Renaming Bulk Files</strong></h1>

<p>In this project, we are going to write a Python program to rename all files within a folder. First, let&#39;s create a folder named demo and put three text files named <strong>file1.txt</strong>, <strong>file2.txt</strong> and <strong>file3.txt</strong> .&nbsp; Let&#39;s start coding this.</p>

<p>First we need to import the <strong>os </strong>library.</p>

<pre>
<code class="language-python">import os</code></pre>

<p>Let&#39;s create a function to function called <strong>rename_files </strong>which takes an argument path.</p>

<pre>
<code class="language-python">def rename_files(path):
    i = 0
    for file in os.listdir(path):
        new_name = f"Hello{i}.txt"
        src = path+file
        new_name = path+new_name
        os.rename(src, new_name)
        i += 1
</code></pre>

<p>In this method, we will iterate over all the files within a given path and use the rename method in os to rename it with the new name given by <strong>f&quot;Hello{i}.txt&quot;</strong>. We are using i as an increment variable.</p>

<p>So, the entire code is now :&nbsp;</p>

<pre>
<code class="language-python">import os


def rename_files(path):
    i = 0
    for file in os.listdir(path):
        new_name = f"Hello{i}.txt"
        src = path+file
        new_name = path+new_name
        os.rename(src, new_name)
        i += 1


if __name__ == "__main__":
    rename_files("Renaming-Bulk-Files/demo/")
</code></pre>

<p>After running the program, all the files will be renamed as <strong>Hello1.txt</strong>, <strong>Hello2.txt</strong> and <strong>Hello3.txt </strong>respectively.</p>

<p>&nbsp;</p>

<h1><strong>Getting Weather Information</strong></h1>

<p>In this project, we are building a weather program that will tell current weather situation in a city or town or any location. So, for us to do this, we will be using <a href="https://openweathermap.org/api">Open Weather Maps API</a>. Just signup for free and get an API Key. We&#39;ll require requests library for this too, and we have already installed that.</p>

<p>Let&#39;s start coding.</p>

<p>First we need to import the libraries :&nbsp;</p>

<pre>
<code class="language-python">import requests
from pprint import pprint
</code></pre>

<p>When we make request on the API, it responds with JSON data which is not easy to read, So, the pprint (pretty print) library will make&nbsp;JSON data readable.</p>

<p>Also, set the below two global variables :&nbsp;</p>

<pre>
<code class="language-python">API_KEY = '1e121683f8158a495a3414b71abcdef'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'</code></pre>

<p>You can get the API Key and Base URL from the above mentioned site.&nbsp;<br />
Now, let&#39;s create a function to get the weather data.</p>

<pre>
<code class="language-python">def get_weather_condition(city):
    query_params = {
        'appid': API_KEY,
        'q': city
    }
    res = requests.get(BASE_URL, params=query_params).json()
    pprint(res)</code></pre>

<p>In the above function, we are first creating a query params dictionary having two key-value pairs called appid and q where appid is the API Key and q is the city which we want to query. Then we are making a GET request to the Base URL with query_params as params and thus our resultant URL will become:&nbsp;</p>

<pre>
<code class="language-bash">https://api.openweathermap.org/data/2.5/weather?appid=API_KEY&amp;q=city</code></pre>

<p>We will get a JSON response and hence we are using the pprint library to make it readable. Our response will look like this :&nbsp;</p>

<pre>
<code class="language-python">{'base': 'stations',
 'clouds': {'all': 75},
 'cod': 200,
 'coord': {'lat': 24.7833, 'lon': 85},
 'dt': 1622302757,
 'id': 1271439,
 'main': {'feels_like': 303.06,
          'humidity': 83,
          'pressure': 1004,
          'temp': 300.1,
          'temp_max': 300.1,
          'temp_min': 300.1},
 'name': 'Gaya',
 'sys': {'country': 'IN',
         'id': 9115,
         'sunrise': 1622244683,
         'sunset': 1622293424,
         'type': 1},
 'timezone': 19800,
 'visibility': 2000,
 'weather': [{'description': 'broken clouds',
              'icon': '04n',
              'id': 803,
              'main': 'Clouds'}],
 'wind': {'deg': 0, 'speed': 0}}</code></pre>

<p>We can see that it responds with the current weather conditions of the city that we asked the data for. We can use this program anywhere like in a GUI application or a web application.</p>

<p>So, our complete program looks like :&nbsp;</p>

<pre>
<code class="language-python">import requests
from pprint import pprint

API_KEY = '1e121683f8158a495a3414b7abcdef'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'


def get_weather_condition(city):
    query_params = {
        'appid': API_KEY,
        'q': city
    }
    res = requests.get(BASE_URL, params=query_params).json()
    pprint(res)


if __name__ == "__main__":
    city = input("Enter city name : ")
    get_weather_condition(city)
</code></pre>

<h1>&nbsp;</h1>

<h1><strong>Password Generator</strong></h1>

<p>In this project, we are going to build a Password Generator that will generate some random passwords of some length.&nbsp;</p>

<p><img src="https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/screenshot-2_swpspz" /></p>

<p>In this project, we&#39;ll be making use of Python&#39;s random module and string module. So, first we need to import them as :</p>

<pre>
<code class="language-python">from random import choice
import string</code></pre>

<p>Since, we&#39;ll be using only the choice method from random module, we have imported it explicitly.</p>

<p>Let&#39;s declare some global variables that we are going to use :&nbsp;</p>

<pre>
<code class="language-python">UPPERCASE = string.ascii_uppercase
LOWECASE = string.ascii_lowercase
NUMBER = string.digits
SYMBOLS = ['@', '#', '$', '%', '&amp;', '_']
DATA = list(UPPERCASE) + list(LOWECASE) + list(NUMBER) + SYMBOLS</code></pre>

<p>Using the string library, we are creating three variables that contains <strong>Uppercase letters</strong>, <strong>Lowercase letters</strong> and <strong>Digits </strong>respectively. Apart from that we are having <strong>Symbols </strong>list that has few symbols. Using all of these four, we are creating a list called <strong>DATA </strong>that we&#39;ll be making use of.</p>

<p>Now, let&#39;s create a method called <strong>generate_random_password</strong> that takes two arguments : <strong>length </strong>and <strong>number</strong>.</p>

<pre>
<code class="language-python">def generate_random_password(length, number):
    print(f"Here are your {number} passwords of length {length} characters :\n")
    for _ in range(number):
        password = ''.join(choice(DATA) for _ in range(length))
        print(password)</code></pre>

<p>Now we are creating a password using the <strong>choice </strong>method that generates a random string of length <strong>length </strong>using the <strong>DATA </strong>list. We are repeating the same for the <strong>number </strong>number of times.</p>

<p>So,our complete program now looks like :&nbsp;</p>

<pre>
<code class="language-python">from random import choice
import string

UPPERCASE = string.ascii_uppercase
LOWECASE = string.ascii_lowercase
NUMBER = string.digits
SYMBOLS = ['@', '#', '$', '%', '&amp;', '_']
DATA = list(UPPERCASE) + list(LOWECASE) + list(NUMBER) + SYMBOLS


def generate_random_password(length, number):
    print(f"Here are your {number} passwords of length {length} characters :\n")
    for _ in range(number):
        password = ''.join(choice(DATA) for _ in range(length))
        print(password)


if __name__ == "__main__":
    number = int(input("How many passwords do you wish to generate ? : "))
    length = int(input("What should be the length of each password ? : "))
    generate_random_password(length, number)
</code></pre>

<p>&nbsp;</p>

<h1><strong>QR Codes in Python</strong></h1>

<p>In this project, we&#39;ll&nbsp;be talking about encoding and decoding QR Codes in Python.</p>

<p>Let&#39;s start by first encoding a QR Code and by encoding we mean, adding some data to a QR Code. For this we have several libraries in Python but we&#39;ll be making use of qrcode library. Also, this library requires Pillow internally. So, first we need to install these&nbsp;packages :&nbsp;</p>

<pre>
<code class="language-bash">pip install qrcode Pillow</code></pre>

<p>Now we can use the qrcode module to create a QR Code.</p>

<pre>
<code class="language-python">def encode_qr(data):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color='black', back_color='white')
    img.save('QR-Codes-in-Python/qrcode.png')</code></pre>

<p>In the above functiion, we are first defining the versionm, box_size and border of the QR code and then adding the data into it. We want a standard QR Code and hence set the colors to black and white and then we are saving the QR code as a PNG image file. Learn more about QR Codes <a href="https://en.wikipedia.org/wiki/QR_code">here</a>.<img src="https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/qrcode_ulwlfp" /></p>

<p>&nbsp;</p>

<p>Now, let&#39;s decode the same QR code. For this, we require another library called pyzbar. So let&#39;s install this.</p>

<pre>
<code class="language-python">pip install pyzbar</code></pre>

<p>Then we can import libraries and create a decode_qr function as :</p>

<pre>
<code class="language-python">from pyzbar.pyzbar import decode
from PIL import Image

def decode_qr(image):
    img = Image.open(image)
    result = decode(img)
    print(result)</code></pre>

<p>This is a simple function which will decode the QR code immediately.</p>

<p>So our complete code becomes :&nbsp;</p>

<pre>
<code class="language-python">import qrcode
from pyzbar.pyzbar import decode
from PIL import Image


def encode_qr(data):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color='black', back_color='white')
    img.save('QR-Codes-in-Python/qrcode.png')


def decode_qr(image):
    img = Image.open(image)
    result = decode(img)
    print(result)


if __name__ == "__main__":
    encode_qr(data=f"Please share this post if you liked this blog.")
    decode_qr('QR-Codes-in-Python/qrcode.png')</code></pre>

<p>&nbsp;</p>

<h2><strong>Conclusion</strong></h2>

<p>Hope, you liked the projects. You can get all the codes <a href="https://github.com/ashutoshkrris/5-Python-Projects">here</a>.</p>
<p>This blog was originally posted on my website <a href="https://iread.ga/posts/25/5-quick-python-projects">here</a></p>