推奨コレクション、22のPythonミニプロジェクト(ソースコード付き)

上の「Pythonクローラーとデータマイニング」をクリックしてフォローしてください

Books」に返信すると、初心者から上級者まで、合計10冊のPythonの電子書籍を受け取ることができます。

鶏肉

スープ

Qin ShimingMoonとHanShiguan、Wanli LongMarchの人々は戻っていません。

Pythonを使用する過程で、私のお気に入りは、多くの操作を完了することができるPythonのさまざまなサードパーティライブラリです。

Pythonプログラミングを学ぶためにPythonで構築された22のプロジェクトがあります。

プロジェクトの目的とプロンプトに応じて独自のソリューションを構築し、プログラミングのレベルを向上させることもできます。

 ダイスシミュレーター

目的:サイコロを振るシミュレーションを行うプログラムを作成します。

ヒント:ユーザーが尋ねたら、ランダムモジュールを使用して1〜6の数値を生成します。

 じゃんけんゲーム

目標:プレイヤーが岩、はさみ、布、およびコンピューターで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)

③ランダム パスワードジェネレータ

目標:パスワードの長さを指定してランダムなパスワードの文字列を生成できるプログラムを作成します。

ヒント:数字の文字列+大文字+小文字+特殊文字を作成します。設定されたパスワードの長さに応じて、パスワードの文字列がランダムに生成されます。

④センテンス ジェネレーター

目的:ユーザーからの入力により、ランダムで一意の文を生成します。

ヒント:ユーザーが入力した名詞、代名詞、形容詞などを入力として受け取り、すべてのデータを文に追加し、それらを組み合わせて返します。

 推測ゲーム

目的:このゲームでのタスクは、範囲内の乱数を生成できるスクリプトを作成することです。ユーザーが3回のチャンスで数字を正しく推測した場合、ユーザーはゲームに勝ちます。そうでない場合、ユーザーは負けます。

ヒント:乱数を生成し、ループを使用してユーザーに3回推測する機会を与え、ユーザーの推測に従って最終結果を出力します。

⑥ストーリー ジェネレーター

目的:ユーザーがプログラムを実行するたびに、ランダムなストーリーが生成されます。

ヒント:ランダムモジュールを使用して、ストーリーのランダムな部分を選択できます。コンテンツは各リストから取得されます。

△メール アドレススライサー

目的:メールアドレスからユーザー名とドメイン名を取得できるPythonスクリプトを作成します。

ヒント:アドレスを2つの文字列に分割するには、@を区切り文字として使用します。

⑧自動的 にメールを送信

目的:メールの送信に使用できるPythonスクリプトを作成します。

ヒント:電子メールライブラリを使用して電子メールを送信できます。

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

 略語

目的:指定された文から頭字語を生成するPythonスクリプトを記述します。

ヒント:分割してインデックスを作成することで最初の単語を取得し、それらを組み合わせることができます。

⑩ワード アドベンチャーゲーム

目的:パスにさまざまなオプションを選択することで、ユーザーが興味深い冒険を楽しめる興味深いPythonスクリプトを作成すること。

 絞首刑執行人

目的:簡単なコマンドライン絞首刑執行人ゲームを作成します。

ヒント:パスワードのリストを作成し、ランダムに単語を選択します。これで、各単語はアンダースコア「_」で表され、ユーザーが単語を推測できるようになります。ユーザーが単語を正しく推測した場合は、「_」を単語に置き換えます。

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

⑫警報 時計

目的:目覚まし時計を作成するPythonスクリプトを作成します。

ヒント:日時モジュールを使用して目覚まし時計を作成し、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

 オーディオブック

目的:Pdfファイルをオーディオブックに変換するPythonスクリプトを作成します。

ヒント:テキストを音声に変換するには、pyttsx3ライブラリを使用します。

インストール:pyttsx3、PyPDF2

⑭ウェザー アプリケーション

目的:Pythonスクリプトを記述して都市名を受け取り、クローラーを使用して都市の天気情報を取得します。

ヒント:Beautifulsoupとrequestsライブラリを使用して、Googleホームページから直接データをクロールできます。

インストール:リクエスト、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)

⑮顔 検出

目的:画像内の顔を検出し、すべての顔をフォルダーに保存できるPythonスクリプトを記述します。

ヒント:haarカスケード分類子を使用して顔を検出できます。返される顔の座標情報はファイルに保存できます。

インストール:OpenCV。

ダウンロード: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+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()

 リマインダーアプリケーション

目的:特定の時間に何か(デスクトップ通知)を行うように通知するリマインダーアプリケーションを作成します。

ヒント: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)     

 ウィキペディアの記事の概要

目的:簡単な方法を使用して、ユーザーが提供した記事のリンクから要約を生成します。

ヒント:クローラーを使用して記事データを取得し、それを抽出して要約を生成できます。

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)

⑱Googleの 検索結果を取得する

目的:クエリ条件に基づいてGoogle検索からデータを取得できるスクリプトを作成します。

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)

得られた結果は以下のとおりです。

⑲通貨 コンバーター

目的:通貨を他のユーザーが選択した通貨に変換できるPythonスクリプトを作成すること。

ヒント:PythonでAPIを使用するか、forex-pythonモジュールを使用してリアルタイムの為替レートを取得します。

インストール:forex-python

 キーロガー

目的:ユーザーが押したすべてのキーをテキストファイルに保存する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()

㉑記事 リーダー

目的:提供されたリンクから記事を自動的に読み取る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

㉒ショート URLジェネレーター

目的:APIを使用して指定されたURLを短縮するPythonスクリプトを記述します。

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

上記は本日共有する内容です。上記の項目については、適切に調整できるものもあります。

たとえば、電子メールを自動的に送信するには、独自のQQメールボックスを使用することを選択できます。

天気情報はいくつかの無料の国内APIを使用することもでき、ウィキペディアはBaidu Baikeに対応でき、Google検索はBaidu検索に対応できます。

これらは誰もが考えることができるものです〜

何千もの川や山がいつも恋をしています。

--- - --- --- --- - --- 終わり --- - --- - --- --- - -

以前の素晴らしい記事の推奨事項:

ようこそ誰もが好きにメッセージを残して、前方、転載をあなたの会社やサポートをありがとうございました

Python学習グループに参加したい場合は、バックグラウンドで返信してください[グループに参加]

何千もの川や山がいつも恋をしています。[見る]をクリックしください。

/本日のメッセージトピック/

一言か二言言ってください~~

おすすめ

転載: blog.csdn.net/pdcfighting/article/details/113798353