学習する価値のある22のPythonミニプログラム(コード付き)

序章

Pythonの豊富な開発エコロジーはその主な利点の1つです。さまざまなサードパーティのライブラリ、フレームワーク、コードはすべて前任者によって作成された「ホイール」であり、多くの操作を完了して開発をより効率的にすることができます。

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

これらの例はシンプルで実用的で、初心者が練習するのに最適です。プロジェクトの目的やヒントに応じて、プログラミングレベルを向上させるために、自分でソリューションを構築することもできます。

より完全なソースコードとPython学習資料を入手したい場合は、このフォント行をクリックしてください。

①ダイス シミュレーター

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

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

②ロック ペーパーはさみゲーム

目標:プレーヤーが岩、はさみ、紙から選択してコンピューターと対戦できるコマンドラインゲームを作成します。プレイヤーが勝った場合、ゲームが終了するまでスコアが追加され、最終スコアがプレイヤーに表示されます。

ヒント:プレーヤーの選択を受け取り、それをコンピューターの選択と比較します。コンピュータの選択は、選択リストからランダムに選択されます。プレイヤーが勝った場合、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とリクエストライブラリを使用して、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 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)

インストール:リクエスト、BeautifulSoup

⑮顔 検出

目的:画像内の顔を検出し、すべての顔をフォルダーに保存できる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を使用するか、WikipediaはBaidu百科事典に対応するか、Google検索はBaidu検索に対応するかなどを選択できます。

これらはすべて、実行時に注意を払う必要があるものです。

 終わり

以上が本日共有した内容です〜お役に立てば幸いです!気に入った場合は、編集者が離れる前に3ストロークを与えることを忘れないでください。

おすすめ

転載: blog.csdn.net/L010409/article/details/123177415