0% found this document useful (0 votes)
47 views

03 Python Projects For Noob 3

Python Projects

Uploaded by

Narendra Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
47 views

03 Python Projects For Noob 3

Python Projects

Uploaded by

Narendra Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 21
Sit back and Relax. Let the Script do the Job. ### Requirements - pandas - plotly Source Code: # importing libraries import pandas as pd import plotly.express as px # storing the dataset data1 = input("Enter first dataset") data2 = input("Enter second dataset") # reading the data data_read_1 = pd.read_excel(data1) data_read_2 = pd.read_excel(data2) # print(df_prices, df_home_1) reference = input("What is the basis of merging? ") data_total = data_read_2.merge(data_read_1, on=reference) # print(df_total) criteria_1 = input("Enter criteria 1") criteria_2 input("Enter criteria 2") fig = px.pie(data_total[[criteria_1, criteria_2]], values=criteria_2, names=criteria_1) fig. show() 12. Store emails in CSV This project contains a simple script to extract email messages from an IMAP server. The messages are written to a simple four-column CSV file. ## Dependencies This depends on the BeautifulSoup library and “Ixml” for extracting text from HTML messages. ## Running the script You will need to have a file “credentials.txt” with your IMAP server account name and password on separate lines. Gmail - and many other IMAP providers - requires you to create a separate “application password” to allow this code to run, so probably do that first. Then put that password in “credentials.txt’. Then simply run python store_emails.py This generates “mails.csv" in the current directory. The generated CSV file contains the following fields for each message: * Date * From (Sender) * Subject * Message text Requirements: beautifulsoup4 Ixml Source code: #!/usr/bin/env python import csv import email from email import policy import imaplib import logging import os import ssl from bs4 import BeautifulSoup credential_path = "credentials.txt" csv_path = "mails.csv" logger = logging.getLogger('imap_poller’) host = "imap.gmail.com" port = 993 ssl_context = ssl.create_default_context() def connect_to_mailbox(): # get mail connection mail = imaplib. MAP4_SSL(host, port, ss]_context=ssl_context) with open(credential_path, “rt") as fr: user = frreadline().strip() pw = frreadline().stripQ) mail.login(user, pw) # get mail box response and select a mail box status, messages = mail.select("INBOX") return mail, messages # get plain text out of html mails def get_text(email_body): soup = BeautifulSoup(email_body, "Ixml") return soup.get_text(separator="\n", strip=True) def write_to_csv(mail, writer, N, total_no_of_mails): for i in range(total_no_of_mails, total_no_of_mails - N, -1): res, data = mail.fetch(str(i), "(RFC822)") response = data[0] if isinstance(response, tuple): msg = email.message_from_bytes(response[1], policy=policy.default) # get header data email_subject = msg["subject"] email_from = msg["from"] email_date = msg["date"] email_text = "" # if the email message is multipart if msg.is_multipart(): # iterate over email parts for part in msg.walk(): # extract content type of email content_type = part.get_content_type() content_disposition = str(part.get("Content-Disposition")) try: # get the email email_body email_body = part.get_payload(decode=True) if email_body: email_text = get_text(email_body.decode(‘utf-8')) except Exception as exc: logger.warning('Caught exception: %r', exc) if ( content_type = "text/plain" and "attachment" not in content_disposition # print text/plain emails and skip attachments # print(email_text) pass elif "attachment" in content_disposition: pass else: # extract content type of email content_type = msg.get_content_type() # get the email email_body email_body = msg.get_payload(decode=True) if email_body: email_text = get_text(email_body.decode('utf-8')) if email_text is not None: # Write data in the csv file row = [email_date, email_from, email_subject, email_text] writer.writerow(row) else: logger.warning('%s:%i: No message extracted’, "INBOX", i) def main(: mail, messages = connect_to_mailbox() logging. basicConfig(level=logging. WARNING) total_no_of_mails = int(messages[0]) # no. of latest mails to fetch # set it equal to total_no_of_emails to fetch all mail in the inbox N=2 with open(csv_path, "wt", encoding="utf-8", newline="") as fw: writer = csv.writer(fw) writer.writerow(["Date", "From", "Subject", "Text mail"]) ty: write_to_csv(mail, writer, N, total_no_of_mails) except Exception as exc: logger.warning(’Caught exception: %r', exc) 13. String search from multiple files Finds a file with the inputted string in the specified folder of your choice. ##H# Prerequisites Python3 is the only prerequisites! No external modules are needed to run. #4 How to run the script In order to run this script you must have Python3 installed, not Python2. The command to run this is simply “python3 findstring.py’, and you'll be prompted with two questions, the string to search, and where to look. Source Code: import os text = input("input text : ") path = input("path : ") # os.chdir(path) def getfiles(path): f=0 os.chdir(path) files = os.listdir() # print(files) for file_name in files: abs_path = os.path.abspath(file_name) if os.path.isdir(abs_path): getfiles(abs_path) if os.path.isfile(abs_path): f = open(file_name, "r") if text in fread(): f=1 print(text + " found in") final_path = os.path.abspath(file_name) print(final_path) return True iff==1: print(text + " not found! ") return False getfiles(path) 14, Take A Break 1. Get or set some favorite URLs for the user 2. measure 2 hours of time that has passed 3. promt the browser to open at one of the set URLs 4. have a loop to do this Source Code files: ‘estrypy operuLpy vatFouepy 15. Terminal-based hangman game This project contains a simple python script to play terminal-based hangman game. ## Prerequisites None ## How to run the script - Run the hangman.py script. - Start to guess the word. Source Code: import random from json import load # function to randomly get one word from words.py and convert the word to uppercase def get_word(): with open(‘words.json’) as json_file: data = load(json_file) wordArray = data["word_list"] word = random.choice(wordArray) word = word.upper() return word # function to play the game def play(word): # intialise variable word_completion = "_" * len(word) # generate a line to show the number of word guessed = False # indicate the status of guess guessed_letters =[] # store guessed letters guessed_words = [] # store guessed words tries = 6 # user have 6 times of wrong # display message and the format of the hangman print("Let's play Hangman!") print(display_hangman(tries)) print(word_completion) print("\n") print("Length of the word: ", len(word)) print("\n") # user can keep guessing when the tries is more than 0 and the answer is not found yet. while not guessed and tries > 0: # Display message and ask for user input and convert it into uppercase guess = input("Please guess a letter or the word: ").upper() # check the length of the user input and is it alpha or not if len(guess) == 1 and guess.isalpha(): # display message when user guess the same letter twice if guess in guessed_letters: print("You already guessed the letter”, guess) # display message and deduct the tries when user guess the wrong letter elif guess not in word: print(guess, "is not in the word.") tries = 1 guessed_letters.append(guess) # dispay message and store the letter when the user guess the correct letter else: print("Good job,", guess, "is in the word!") guessed_letters.append(guess) word_as_list = list(word_completion) indices = [i for i, letter in enumerate(word) if letter == guess] for index in indices: word_as_list{index] = guess # join the guess word in the word_completion word_completion = "" join(word_as_list) # if there is not blank space in word_completion change the status of guess to true if "_" not in word_completion: guessed = True # check the length of the user input and is it alpha or not elif len(guess) == len(word) and guess.isalpha(): # display message when user guess the same letter twice if guess in guessed_words: print("You already guessed the word", guess) # display message and deduct the tries when user guess the wrong letter elif guess != word: print(guess, "is not the word.") tries -= 1 guessed_words.append(guess) # change the status of guess else: guessed = True word_completion = word # display error message for user else: print(""Not a valid guess.") # display the format of hangman each time of guess print(display_hangman(tries)) print(word_completion) print("\n") print("Length of the word: ", len(word)) print("\n") # if the variable of guess is true means user win the game if guessed: print(""Congrats, you guessed the word! You win!") # else means user lose the game. else: print("Sorry, you ran out of tries. The word was " + word +". Maybe next time!") # function to display the format of hangman def display_hangman(tries): stages = [ w WW ] return stages|tries] # main function to start the game

You might also like