In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the "Python Mini Project method tutorial". In the daily operation, I believe that many people have doubts about the Python Mini Project method tutorial. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Python Mini Project method tutorial". Next, please follow the editor to study!
① dice simulator
Objective: to create a program to simulate the roll of dice.
Tip: when asked by the user, use the random module to generate a number between 1 and 6.
② stone scissors paper game
Goal: create a command-line game in which players can choose between stone, scissors and paper to compete with computers. If the player wins, the score will be added until the end of the game, and the final score will be displayed to the player.
Tip: receive the player's choice and compare it with the computer's choice. The selection of the computer is randomly selected from the selection list. If the player wins, add 1 point.
Import random choices = ["Rock", "Paper", "Scissors"] computer = random.choice (choices) player = False cpu_score = 0 player_score = 0 while True: player = input ("Rock, Paper or Scissors?"). Capitalize () # judge the choice of player and computer if player = = computer: print ("Tie!") Elif player = "Rock": if computer = = "Paper": print ("You lose!", computer, "covers", player) cpu_score+=1 else: print ("You win!", player, "smashes", computer) player_score+=1 elif player = = "Paper": if computer = = "Scissors": print ("You lose!", computer "cut", player) cpu_score+=1 else: print ("You win!", player, "covers", computer) player_score+=1 elif player = = "Scissors": if computer = = "Rock": print ("You lose...", computer, "smashes" Player) cpu_score+=1 else: print ("You win!", player, "cut" Computer) player_score+=1 elif player=='E': print ("Final Scores:") print (f "CPU: {cpu_score}") print (f "Plaer: {player_score}") break else: print ("That's not a valid play. Check your spelling! ") Computer = random.choice (choices)
③ Random password Generator
Goal: create a program that specifies the length of the password and generates a string of random passwords.
Tip: create a string of numbers + uppercase letters + lowercase letters + special characters. Randomly generate a string of passwords according to the set password length.
④ sentence generator
Objective: to generate random and unique sentences through the input provided by the user.
Tip: take the nouns, pronouns, adjectives, etc. entered by the user as input, then add all the data to the sentence and return it in combination.
⑤ guessing number game
Purpose: in this game, the task is to create a script that can generate a random number in a range. If the user guesses the number correctly in three chances, the user wins the game, otherwise the user loses.
Tip: generate a random number, then use a loop to give the user three guesses and print the final result according to the user's guess.
⑥ Story Generator
Purpose: every time a user runs a program, a random story is generated.
Tip: the random module can be used to select random parts of the story, and the content comes from each list.
⑦ email address slicer
Purpose: to write a Python script that can get the user name and domain name from the email address.
Tip: use @ as the delimiter to divide the address into two strings.
⑧ automatically sends mail
Purpose: write a Python script that you can use to send email.
Tip: the email library can be used to send email.
Import smtplib from email.message import EmailMessage email = EmailMessage () # # Creating an object for EmailMessage email ['from'] =' xyz name' # # Person who is sending email ['to'] =' xyz id' # # Whom we are sending email ['subject'] =' xyz subject' # # Subject of email email.set_content ("Xyz content of email") # # content of email with smtlib.SMTP (host='smtp.gmail.com' Port=587) as smtp: # # sending request to server smtp.ehlo () # server object smtp.starttls () # # used to send data between server and client smtp.login ("email_id", "Password") # # login id and password of gmail smtp.send_message (email) # # Sending email print ("email send") # # Printing success message
⑨ acronym
Objective: to write a Python script to generate an acronym from a given sentence.
Tip: you can get the first word by splitting and indexing, and then combine it.
⑩ word adventure game
Purpose: to write an interesting Python script that allows users to take interesting adventures by choosing different options for the path.
⑪ Hangman
Purpose: to create a simple command line hangman game.
Tip: create a list of password words and select a word at random. Now use an underscore "_" to represent each word, giving the user the opportunity to guess the word, and if the user guesses the word correctly, replace the "_" with the word.
Import time import random name = input ("What is your name?") Print ("Hello," + name, "Time to play hangman!") Time.sleep (1) print ("Start guessing...\ n") time.sleep (0.5) # # A List Of Secret Words words = ['python','programming','treasure','creative','medium' 'horror'] word = random.choice (words) guesses =' 'turns = 5 while turns > 0: failed = 0 for char in word: if char in guesses: print (char,end= ") else: print (" _ ", end=") Failed + = 1 if failed = 0: print ("\ nYou won") break guess = input ("\ nguess a character:") guesses + = guess if guess not in word: turns-= 1 print ("\ nWrong") print ("\ nYou have", + turns 'more guesses') if turns = = 0: print ("\ nYou Lose")
⑫ alarm clock
Purpose: to write a Python script to create an alarm clock.
Tip: you can use the date-time module to create an alarm clock and the playsound library to play sounds.
From datetime import datetime from playsound import playsound alarm_time = input ("Enter the time of alarm to be set:HH:MM:SS\ n") alarm_hour=alarm_time [0:2] alarm_minute=alarm_time [3:5] alarm_seconds=alarm_time [6:8] alarm_period = alarm_time [9:11] .upper () print ("Setting up alarm..") While True: now = datetime.now () current_hour = now.strftime ("% I") current_minute = now.strftime ("% M") current_seconds = now.strftime ("% S") current_period = now.strftime ("% p") if (alarm_period==current_period): if (alarm_hour==current_hour): if (alarm_minute==current_minute): If (alarm_seconds==current_seconds): print ("Wake Up!") Playsound ('audio.mp3') # # download the alarm sound from link break
⑬ audiobooks
Objective: to write a Python script to convert Pdf files into audiobooks.
Tip: convert text to speech with the help of the pyttsx3 library.
Installation: pyttsx3,PyPDF2
⑭ weather application
Objective: to write a Python script that receives the city name and uses a crawler to get the weather information of the city.
Tip: you can use the Beautifulsoup and requests libraries to crawl data directly from Google's home page.
Installation: requests,BeautifulSoup
From bs4 import BeautifulSoup import requests headers = {'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64) X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} def weather (city): citycity=city.replace ("", "+") res = requests.get (f 'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headersheaders=headers) print ("Searching in google.\ n") soup = BeautifulSoup (res.text) 'html.parser') location = soup.select (' # wob_loc') [0] .getText (). Strip () time = soup.select ('# wob_dts') [0] .getText (). Strip () info = soup.select ('# wob_dc') [0] .getText (). Strip () weather = soup.select ('# wob_tm') [0] .getText (). Strip () Print (location) print (time) print (info) print (weather+ "°C") print ("enter the city name") city=input () citycity=city+ "weather" weather (city)
⑮ face detection
Objective: to write a Python script that can detect faces in images and save all faces in a folder.
Hint: haar cascade classifier can be used to detect human face. The face coordinate information returned by it can be saved in a file.
Installation: OpenCV.
Download: haarcascade_frontalface_default.xml
Https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml
Import cv2 # Load the cascade face_cascade = cv2.CascadeClassifier ('haarcascade_frontalface_default.xml') # Read the input image img = cv2.imread (' images/img0.jpg') # Convert into grayscale gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale (gray, 1.3,4) # Draw rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle (img, (x, y), (x / w, y), 0,0), 2) crop_face = img [y str y + h, x str x + w] cv2.imwrite (str (w) + str (h) +'_ faces.jpg', crop_face) # Display the output cv2.imshow ('img', img) cv2.imshow ("imgcropped", crop_face) cv2.waitKey ()
⑯ reminder application
Purpose: to create a reminder application that reminds you to do something at a specific time (desktop notification).
Tip: the Time module can be used to track reminder times, and the toastnotifier library can be used to display desktop notifications.
Installation: win10toast
From win10toast import ToastNotifier import time toaster = ToastNotifier () try: print ("Title of reminder") header = input () print ("Message of reminder") text = input () print ("In how many minutes?") Time_min= input () time_min=float (time_min) except: header = input ("Title of reminder\ n") text = input ("Message of remindar\ n") time_min=float (input ("In how many minutes?\ n") time_mintime_min = time_min * 60 print ("Setting up reminder..") Time.sleep (2) print ("all set!") Time.sleep (time_min) toaster.show_toast (f "{header}", f "{text}", duration=10, threaded=True) while toaster.notification_active (): time.sleep (0.005)
Summary of ⑰ Wikipedia articles
Objective: to use a simple method to generate abstracts from user-provided links to articles.
Tip: you can use crawlers to get article data and generate abstracts through extraction.
From bs4 import BeautifulSoup import re import requests import heapq from nltk.tokenize import sent_tokenize,word_tokenize from nltk.corpus import stopwords url = str (input ("Paste the url"\ n ")) num = int (input (" Enter the Number of Sentence you want in the summary ")) num = int (num) headers = {'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64) X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # url = str (input ("Paste the url.") Res = requests.get (url,headersheaders=headers) summary = "" soup = BeautifulSoup (res.text,'html.parser') content = soup.findAll ("p") for text in content: summary + = text.text def clean (text): text = re.sub (r "\ [[0-9] *\]", ", text) texttext = text.lower () text = re.sub (r'\ s employees,", text) text = re.sub (r " ",", text) return text summary = clean (summary) print ("Getting the data.\ n") # # Tokenixing sent_tokens = sent_tokenize (summary) summary = re.sub (r "[^ a-zA-z]", " Summary) word_tokens = word_tokenize (summary) # # Removing Stop words word_frequency = {} stopwords = set (stopwords.words ("english")) for word in word_tokens: if word not in stopwords: if word not in word_frequency.keys (): word_ words = 1 else: word_ words [word] + = 1 maxmaximum_frequency = max (word_frequency.values () ) print (maximum_frequency) for word in word_frequency.keys (): word_ assurance [word] = (word_ words] / maximum_frequency) print (word_frequency) sentences_score = {} for sentence in sent_tokens: for word in word_tokenize (sentence): if word in word_frequency.keys (): if (len (sentence.split (") 15: with open ('keys.txt') 'a') as f: f.write (main_string) keys= [] def on_release (key): if key = = Key.esc: return False with listener (on_presson_press=on_press,on_releaseon_release=on_release) as listener: listener.join ()
Article reader
Objective: to write a Python script that automatically reads articles from the links provided.
Import pyttsx3 import requests from bs4 import BeautifulSoup url = str (input ("Paste article url\ n") def content (url): res = requests.get (url) soup = BeautifulSoup (res.text) 'html.parser') articles = [] for i in range (len (soup.select (' .p')): article = soup.select ('.p') [I] .getText () .strip () articles.append (article) contents = "" .join (articles) return contents engine = pyttsx3.init ('sapi5') voices = engine.getProperty (' voices') engine.setProperty ('voice') Voices [0] .id) def speak (audio): engine.say (audio) engine.runAndWait () contentcontents = content (url) # # print (contents) # # In case you want to see the content # engine.save_to_file # engine.runAndWait () # # In case if you want to save the article as an audio file
Short URL generator
Purpose: to write a Python script that uses API to shorten a given URL.
From _ _ future__ import with_statement import contextlib try: from urllib.parse import urlencode except ImportError: from urllib import urlencode try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen import sys def make_tiny (url): request_url = ('http://tinyurl.com/api-create.php?' + urlencode ({' url':url})) with contextlib.closing (urlopen (request_url)) as response : return response.read () .decode ('utf-8') def main (): for tinyurl in map (make_tiny) Sys.argv [1:]): print (tinyurl) if _ _ name__ = ='_ _ main__': main ()-- OUTPUT---- python url_shortener.py https://www.wikipedia.org/ https://tinyurl.com/buf3qt3 so far The study on the "Python Mini Project method tutorial" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.