1. 程式人生 > 其它 >建議收藏!獻給Python初學者的22個入門小專案,練手必備!

建議收藏!獻給Python初學者的22個入門小專案,練手必備!

Python的各種第三方庫,能夠完成很多好玩的操作,給大家展現幾個Python實現的小玩意,看看大家都做過沒~

大家也可根據專案的目的及提示,自己構建解決方法,一起在評論區交流~

1、短網址生成器

編寫一個Python指令碼,使用API縮短給定的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

兄弟們學習python,有時候不知道怎麼學,從哪裡開始學。掌握了基本的一些語法或者做了兩個案例後,不知道下一步怎麼走,不知道如何去學習更加高深的知識。
那麼對於這些大兄弟們,我準備了大量的免費視訊教程,PDF電子書籍,以及視訊源的原始碼!
還會有大佬解答!
都在這個群裡了

點這裡立即進裙
歡迎加入,一起討論 一起學習!

2、故事生成器

每次使用者執行程式時,都會生成一個隨機的故事。

random模組可以用來選擇故事的隨機部分,內容來自每個列表裡。

import random
when=['A few years ago''Yesterday''Last night', 'A long time ago' , 'On 20th Jan']
who=['a rabbit','an elephant', 'a mouse', 'a turtle', 'a cat']
name=[ 'Ali '"Miriam' , "danicL','Hoouk",‘Starwalker'1
residence-[ 'Barcelona' , " India','Germany','Venice', 'England']
went= [ 'cinema',"university' , ' seminar', 'school','laundry ']
happened =['made a lot of friends' , 'Eats a burger','found a secret key', ' solved a mistery'" wrote a book"]
print( random.choice(when) + ',' +random.choice(who) + ' that lived in ' +
random.choice(residence) +', went to the ' + random.choice(went) + ' and ' +
random.choice(happened))
-----------------------------------------OUTPUT-----------------------------------------
A long time ago, a cat that lived in England, went to the seminar and solved a mistery

3、郵件地址切片器

編寫一個Python指令碼,可以從郵件地址中獲取使用者名稱和域名。

使用@作為分隔符,將地址分為分為兩個字串。

#Get the user 's email address
email = input("what is your email address ?: ").strip()
# Slice out the user name
email = input("what is your email address ?: ").strip()
# Slice out the user name
domain_name = email[email.index("a")+1:]
#Format message
res = f"Your username is '{user_name}’ and your domain name is '{domain_name}"
# Display the result message
print(res)
--------------------------------OUTPUT------------------------------------------
what is your email address?: karl31agmail.com
Your username is "karl31" and your domain name is 'gmail.com

4、句子生成器

通過使用者提供的輸入,來生成隨機且唯一的句子。

以使用者輸入的名詞、代詞、形容詞等作為輸入,然後將所有資料新增到句子中,並將其組合返回。

color = input("Enter a color:“)
pluralNoun= input("Enter a plural noun: ")
celebrity input("Enter a celebrity: ")
print("Roses are" ,color)
print(pluralNoun+ " are blue")
print(I love" , celebrity)
-----------------------------------------------
Red
Teeth
RDJ
Roses are red. teeth are blue. I Love RDJ

5、自動傳送郵件

編寫一個Python指令碼,可以使用這個指令碼傳送電子郵件。

email庫可用於傳送電子郵件。

import smtplib 
from email.message import EmailMessage
email = EmailMessage() ## Creating a 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

6、猜數字遊戲

在這個遊戲中,任務是建立一個指令碼,能夠在一個範圍內生成一個隨機數。如果使用者在三次機會中猜對了數字,那麼使用者贏得遊戲,否則使用者輸。

生成一個隨機數,然後使用迴圈給使用者三次猜測機會,根據使用者的猜測列印最終的結果。

import random
nunber = random.randint(1,10)
for i in range(e,3):
    user =int(input("guess the number"))
    if user -number:
       print("Hurray H")
       print(f"you guessed the number right it's {number}")
       break
    elif user>number:
       print("Your guess is too high")
    elif userenuimber:
       print(Your guess is too low.")
else:
    print(f"Nice Try!,but the number is {number}")

7、石頭剪刀布遊戲

建立一個命令行遊戲,遊戲者可以在石頭、剪刀和布之間進行選擇,與計算機PK。如果遊戲者贏了,得分就會新增,直到結束遊戲時,最終的分數會展示給遊戲者。

接收遊戲者的選擇,並且與計算機的選擇進行比較。計算機的選擇是從選擇列表中隨機選取的。如果遊戲者獲勝,則增加1分。

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()
    # 判斷遊戲者和電腦的選擇
    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)

8、維基百科文章摘要

使用一種簡單的方法從使用者提供的文章連結中生成摘要。

你可以使用爬蟲獲取文章資料,通過提取生成摘要。

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,headers=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)
    text = text.lower()    text = re.sub(r'\s+'," ",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_frequency[word]=1
        else:
            word_frequency[word] +=1
maximum_frequency = max(word_frequency.values())
print(maximum_frequency)          
for word in word_frequency.keys():
    word_frequency[word] = (word_frequency[word]/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(" "))) <30:
                if sentence not in sentences_score.keys():
                    sentences_score[sentence] = word_frequency[word]
                else:
                    sentences_score[sentence] += word_frequency[word]

print(max(sentences_score.values()))
def get_key(val): 
    for key, value in sentences_score.items(): 
        if val == value: 
            return key 
key = get_key(max(sentences_score.values()))print(key+"\n")
print(sentences_score)
summary = heapq.nlargest(num,sentences_score,key=sentences_score.get)print(" ".join(summary))summary = " ".join(summary)

9、隨機密碼生成器

建立一個程式,可指定密碼長度,生成一串隨機密碼。

建立一個數字+大寫字母+小寫字母+特殊字元的字串。根據設定的密碼長度隨機生成一串密碼。

import random
passlen = int(input("enter the length of password"))
s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLNNOPQRSTUVWXYz!簡#$x^6a()?p=.join(random.sample(s.passlen )
print(p)
-----------------------------------------------------------
enter the length of password6
za1gBe

10、鬧鐘

編寫一個建立鬧鐘的Python指令碼。

你可以使用date-time模組建立鬧鐘,以及playsound庫播放聲音。

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

11、文字冒險遊戲

編寫一個有趣的Python指令碼,通過為路徑選擇不同的選項讓使用者進行有趣的冒險。

name = str( input("Enter Your Mame\n"))
print(f"{name} you are stuck in a forest.Your task is to get out from the forest withoutdieing")
print("You are walking threw forest and suddenly a wolf comes in your way.Now Youoptions.")
print("1.Run 2. climb The Nearest Tree ")
user = int(input("choose one option 1 or 2"))
if user = 1:
    print("You Died!!")
elif user = 2:
    print("You Survived!!")
else:
    print("Incorrect Input")
#### Add a loop and increase the story as much as you can

12、有聲讀物

編寫一個Python指令碼,用於將Pdf檔案轉換為有聲讀物。

藉助pyttsx3庫將文字轉換為語音。

要安裝的模組:

pyttsx3
PyPDF2
import pyttsx3,PyPDF2
DdfReader = pyPDF2.PdfFileReader(open( "file.pdf',"rb'))
speaker = pyttsx3.init()
for page_num in range(pdfReader.numPages):
    text =pdfReader.getPage(page_num).extractText()
    speaker.say(text)
    speaker.runAndwait()
speaker.stopo()

13、貨幣換算器

編寫一個Python指令碼,可以將一種貨幣轉換為其他使用者選擇的貨幣。

使用Python中的API,或者通過forex-python模組來獲取實時的貨幣匯率。

安裝:forex-python

from forex _python.converter import CurrencyRatesc = CurrencyRates()
amount = int(input("Enter The Amount You Want To Convert\n"))
from_currency = input( "From\n" )-upper()
to_currency = input( "To\n").upper()
print(from_currency,"To",to_currency , amount)
result = c.convert(from_currency, to_currency, amount)
print(result)

14、天氣應用

編寫一個Python指令碼,接收城市名稱並使用爬蟲獲取該城市的天氣資訊。

你可以使用Beautifulsoup和requests庫直接從谷歌主頁爬取資料。

安裝:

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):
    city=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',headers=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()
city=city+" weather"
weather(city)

15、人臉檢測

編寫一個Python指令碼,可以檢測影象中的人臉,並將所有的人臉儲存在一個資料夾中。

可以使用haar級聯分類器對人臉進行檢測。它返回的人臉座標資訊,可以儲存在一個檔案中。

安裝:

OpenCV

下載: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+h), (255, 0, 0), 2)
    crop_face = img[y:y + h, x: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()

16、提醒應用

建立一個提醒應用程式,在特定的時間提醒你做一些事情(桌面通知)。
Time模組可以用來跟蹤提醒時間,toastnotifier庫可以用來顯示桌面通知。

安裝: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_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)    

17、Hangman

建立一個簡單的命令列hangman遊戲。

建立一個密碼詞的列表並隨機選擇一個單詞。現在將每個單詞用下劃線“”表示,給使用者提供猜單詞的機會,如果使用者猜對了單詞,則將“”用單詞替換。

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") 

18、文章朗讀器

編寫一個Python指令碼,自動從提供的連結讀取文章。

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()

contents = 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 a audio file

19、獲取谷歌搜尋結果

建立一個指令碼,可以根據查詢條件從谷歌搜尋獲取資料。

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 google(query):
    query = query.replace(" ","+")
    try:
        url = f'https://www.google.com/search?q={query}&oq={query}&aqs=chrome..69i57j46j69i59j35i39j0j46j0l2.4948j0j7&sourceid=chrome&ie=UTF-8'
        res = requests.get(url,headers=headers)
        soup = BeautifulSoup(res.text,'html.parser')
    except:
        print("Make sure you have a internet connection")
    try:
        try:
            ans = soup.select('.RqBzHd')[0].getText().strip()

        except:
            try:
                title=soup.select('.AZCkJd')[0].getText().strip()
                try:
                    ans=soup.select('.e24Kjd')[0].getText().strip()
                except:
                    ans=""
                ans=f'{title}\n{ans}'

            except:
                try:
                    ans=soup.select('.hgKElc')[0].getText().strip()
                except:
                    ans=soup.select('.kno-rdesc span')[0].getText().strip()

    except:
        ans = "can't find on google"
    return ans

result = google(str(input("Query\n")))
print(result)

獲取結果如下


20、鍵盤記錄器

編寫一個Python指令碼,將使用者按下的所有鍵儲存在一個文字檔案中。

pynput是Python中的一個庫,用於控制鍵盤和滑鼠的移動,它也可以用於製作鍵盤記錄器。簡單地讀取使用者按下的鍵,並在一定數量的鍵後將它們儲存在一個文字檔案中。

from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()


keys=[]
def on_press(key):
    global keys
    #keys.append(str(key).replace("'",""))
    string = str(key).replace("'","")
    keys.append(string)
    main_string = "".join(keys)
    print(main_string)
    if len(main_string)>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_press=on_press,on_release=on_release) as listener:
    listener.join()

21、縮寫詞

編寫一個Python指令碼,從給定的句子生成一個縮寫詞。

你可以通過拆分和索引來獲取第一個單詞,然後將其組合。

text = str(input("Enter a stringin"))
text = text.splitO
acronym = ""
for i in text:
acronym = acronymstr(i[e3).upperOprint(acronym)
-----------------output--------------------------
Python Programming languagePPL

22、骰子模擬器

建立一個程式來模擬擲骰子

當用戶詢問時,使用random模組生成一個1到6之間的數字。

import random;
while int(input( ' Press 1 to roll the dice or 0 to exit:\n')): print(random.randint(1,6))
-----------------------------------------------

Press 1 to roll the dice or 0 to exit
1
4

以上就是今天分享的內容,針對上面這些專案,有的可以適當調整。歡迎大家在評論區一起交流!