0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

7. 実践的なプロジェクト

  • これまでに学んだ概念を使用した小規模プロジェクト

実践的なプロジェクトは、これまでに学んだPythonの概念を実際のアプリケーションに適用する素晴らしい機会です。以下に、異なる難易度レベルの3つのプロジェクト例を示します。各プロジェクトには、主要な機能を実装するサンプルコードを含めています。

1. 簡単: To-Doリストアプリケーション

このプロジェクトでは、基本的なデータ構造、入出力、関数を使用します。

tasks = []

def add_task(task):
    tasks.append(task)
    print(f"タスク '{task}' を追加しました。")

def remove_task(task):
    if task in tasks:
        tasks.remove(task)
        print(f"タスク '{task}' を削除しました。")
    else:
        print(f"タスク '{task}' が見つかりません。")

def show_tasks():
    if tasks:
        print("現在のタスク:")
        for i, task in enumerate(tasks, 1):
            print(f"{i}. {task}")
    else:
        print("タスクはありません。")

while True:
    print("\n1: タスクを追加")
    print("2: タスクを削除")
    print("3: タスクを表示")
    print("4: 終了")
    choice = input("選択してください (1-4): ")

    if choice == '1':
        task = input("新しいタスクを入力してください: ")
        add_task(task)
    elif choice == '2':
        task = input("削除するタスクを入力してください: ")
        remove_task(task)
    elif choice == '3':
        show_tasks()
    elif choice == '4':
        print("アプリケーションを終了します。")
        break
    else:
        print("無効な選択です。もう一度試してください。")

このアプリケーションでは、リスト、関数、ループ、条件文を使用しています。ユーザーはタスクの追加、削除、表示、およびプログラムの終了ができます。

2. 中級: 簡単な家計簿アプリケーション

このプロジェクトでは、クラス、ファイル入出力、および例外処理を使用します。

import json
from datetime import datetime

class BudgetTracker:
    def __init__(self, filename):
        self.filename = filename
        self.transactions = self.load_transactions()

    def load_transactions(self):
        try:
            with open(self.filename, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return []

    def save_transactions(self):
        with open(self.filename, 'w') as f:
            json.dump(self.transactions, f)

    def add_transaction(self, amount, category, description):
        transaction = {
            'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'amount': amount,
            'category': category,
            'description': description
        }
        self.transactions.append(transaction)
        self.save_transactions()

    def get_balance(self):
        return sum(transaction['amount'] for transaction in self.transactions)

    def get_transactions_by_category(self, category):
        return [t for t in self.transactions if t['category'] == category]

def main():
    tracker = BudgetTracker('transactions.json')

    while True:
        print("\n1: 取引を追加")
        print("2: 残高を確認")
        print("3: カテゴリ別取引を表示")
        print("4: 終了")
        choice = input("選択してください (1-4): ")

        if choice == '1':
            try:
                amount = float(input("金額を入力してください (収入は正、支出は負): "))
                category = input("カテゴリを入力してください: ")
                description = input("説明を入力してください: ")
                tracker.add_transaction(amount, category, description)
                print("取引が追加されました。")
            except ValueError:
                print("無効な金額です。もう一度試してください。")

        elif choice == '2':
            print(f"現在の残高: {tracker.get_balance():.2f}")

        elif choice == '3':
            category = input("表示するカテゴリを入力してください: ")
            transactions = tracker.get_transactions_by_category(category)
            if transactions:
                for t in transactions:
                    print(f"{t['date']} - {t['amount']:.2f} - {t['description']}")
            else:
                print(f"{category}カテゴリの取引はありません。")

        elif choice == '4':
            print("アプリケーションを終了します。")
            break

        else:
            print("無効な選択です。もう一度試してください。")

if __name__ == "__main__":
    main()

このアプリケーションでは、クラス、ファイル入出力(JSON形式)、例外処理、および日付処理を使用しています。ユーザーは取引の追加、残高の確認、カテゴリ別の取引表示ができます。

3. 上級: 簡単なWebスクレイピングと分析ツール

このプロジェクトでは、外部ライブラリの使用、Webスクレイピング、データ分析、およびデータの可視化を行います。

import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter

def scrape_news_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    headlines = soup.find_all('h2', class_='headline')
    return [headline.text.strip() for headline in headlines]

def analyze_headlines(headlines):
    # 単語の出現頻度を計算
    words = ' '.join(headlines).lower().split()
    word_freq = Counter(words)
    
    # 最も頻繁に出現する10語を取得
    top_words = dict(word_freq.most_common(10))
    
    return top_words

def visualize_results(data):
    df = pd.DataFrame(list(data.items()), columns=['Word', 'Frequency'])
    plt.figure(figsize=(10, 6))
    plt.bar(df['Word'], df['Frequency'])
    plt.title('Top 10 Most Frequent Words in Headlines')
    plt.xlabel('Words')
    plt.ylabel('Frequency')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig('word_frequency.png')
    print("結果が'word_frequency.png'として保存されました。")

def main():
    url = input("ニュースサイトのURLを入力してください: ")
    try:
        headlines = scrape_news_headlines(url)
        print(f"{len(headlines)}件の見出しを取得しました。")
        
        analysis_result = analyze_headlines(headlines)
        print("\n最も頻繁に出現する10語:")
        for word, freq in analysis_result.items():
            print(f"{word}: {freq}")
        
        visualize_results(analysis_result)
    except Exception as e:
        print(f"エラーが発生しました: {e}")

if __name__ == "__main__":
    main()

このアプリケーションでは、以下の外部ライブラリを使用しています:

  • requests: Webページの取得
  • BeautifulSoup: HTMLの解析
  • pandas: データ処理
  • matplotlib: データの可視化

スクリプトは指定されたニュースサイトから見出しをスクレイピングし、最も頻繁に出現する単語を分析して、結果をグラフとして表示します。

これらのプロジェクトは、Pythonの様々な概念を実践的に適用する方法を示しています。難易度に応じて選択し、必要に応じて機能を追加または変更することができます。プロジェクトを通じて学ぶことで、プログラミングスキルを効果的に向上させることができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?