【python】クローラー型検索エンジン

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import sqlite3
import threading
import queue
import tkinter as tk
from tkinter import ttk, messagebox

# データベース設定
DB_NAME = "gui_search_engine.db"
conn = sqlite3.connect(DB_NAME, check_same_thread=False)
cursor = conn.cursor()

# テーブル作成
cursor.execute("""
CREATE TABLE IF NOT EXISTS pages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    url TEXT UNIQUE,
    title TEXT,
    description TEXT,
    content TEXT
)
""")
conn.commit()

# グローバル変数
visited = set()
visited_lock = threading.Lock()
task_queue = queue.Queue()
MAX_THREADS = 5

# ページをデータベースに保存
def save_page_to_db(url, title, description, content):
    try:
        cursor.execute("INSERT INTO pages (url, title, description, content) VALUES (?, ?, ?, ?)",
                       (url, title, description, content))
        conn.commit()
    except sqlite3.IntegrityError:
        pass  # URL重複時は無視

# URL正規化
def normalize_url(base, link):
    return urljoin(base, link).split('#')[0]

# クローラー
def crawl(url, domain, status_label):
    with visited_lock:
        if url in visited:
            return
        visited.add(url)

    try:
        response = requests.get(url, timeout=10)
        soup = BeautifulSoup(response.content, "html.parser")

        # メタデータ収集
        title = soup.title.string if soup.title else "No Title"
        description_tag = soup.find("meta", attrs={"name": "description"})
        description = description_tag["content"] if description_tag else "No Description"
        content = soup.get_text()

        # データベースに保存
        save_page_to_db(url, title, description, content)

        # ステータス更新
        status_label.config(text=f"Crawling: {url}")

        # 次のURLを収集
        for link in soup.find_all('a', href=True):
            full_url = normalize_url(url, link['href'])
            if urlparse(full_url).netloc == domain:
                task_queue.put(full_url)
    except Exception as e:
        print(f"Error crawling {url}: {e}")

# 並列クローリング
def start_crawling(start_url, domain, status_label):
    visited.clear()
    task_queue.put(start_url)

    def worker():
        while not task_queue.empty():
            url = task_queue.get()
            crawl(url, domain, status_label)
        status_label.config(text="Crawling Complete")

    threads = []
    for _ in range(MAX_THREADS):
        thread = threading.Thread(target=worker)
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()

# 検索機能
def search(query, results_box):
    cursor.execute("SELECT url, title, description FROM pages WHERE content LIKE ?", (f"%{query}%",))
    results = cursor.fetchall()
    results_box.delete(*results_box.get_children())  # 結果をクリア

    if not results:
        messagebox.showinfo("検索結果", "該当する結果はありませんでした。")
    else:
        for url, title, description in results:
            results_box.insert("", "end", values=(title, url, description[:100]))

# GUI設計
def create_gui():
    root = tk.Tk()
    root.title("クローラー型検索エンジン")

    # フレーム構成
    frame_crawl = ttk.Frame(root, padding=10)
    frame_crawl.grid(row=0, column=0, sticky="ew")
    frame_search = ttk.Frame(root, padding=10)
    frame_search.grid(row=1, column=0, sticky="nsew")

    # クローリングセクション
    ttk.Label(frame_crawl, text="スタートURL:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
    url_entry = ttk.Entry(frame_crawl, width=50)
    url_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")

    status_label = ttk.Label(frame_crawl, text="Status: Ready", foreground="blue")
    status_label.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="w")

    def on_crawl():
        start_url = url_entry.get().strip()
        if not start_url:
            messagebox.showerror("Error", "スタートURLを入力してください。")
            return

        # スキーム補完
        if not start_url.startswith(("http://", "https://")):
            start_url = "https://" + start_url

        # ドメインを取得
        domain = urlparse(start_url).netloc
        status_label.config(text="Crawling in Progress...")
        threading.Thread(target=start_crawling, args=(start_url, domain, status_label)).start()

    ttk.Button(frame_crawl, text="クローリング開始", command=on_crawl).grid(row=0, column=2, padx=5, pady=5)

    # 検索セクション
    ttk.Label(frame_search, text="検索クエリ:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
    query_entry = ttk.Entry(frame_search, width=30)
    query_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")

    results_box = ttk.Treeview(frame_search, columns=("Title", "URL", "Description"), show="headings")
    results_box.heading("Title", text="タイトル")
    results_box.heading("URL", text="URL")
    results_box.heading("Description", text="説明")
    results_box.grid(row=1, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")

    def on_search():
        query = query_entry.get().strip()
        if not query:
            messagebox.showerror("Error", "検索クエリを入力してください。")
            return
        search(query, results_box)

    ttk.Button(frame_search, text="検索", command=on_search).grid(row=0, column=2, padx=5, pady=5)

    # ウィンドウサイズ調整
    root.columnconfigure(0, weight=1)
    frame_search.rowconfigure(1, weight=1)

    root.mainloop()

# GUI起動
if __name__ == "__main__":
    create_gui()

    # データベース接続を閉じる
    conn.close()

二次元画像生成AI python

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from tqdm import tqdm

# データセットの変換(リサイズと正規化)
transform = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))  # ピクセル値を[-1, 1]の範囲にスケーリング
])

# AnimeFaceDatasetのロード
dataset = datasets.ImageFolder(root='C:/Users/tyosu/projects/anime_faces',transform=transform)
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)

# Generator(生成モデル)
class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()
        self.main = nn.Sequential(
            nn.Linear(100, 256),
            nn.ReLU(True),
            nn.Linear(256, 512),
            nn.ReLU(True),
            nn.Linear(512, 1024),
            nn.ReLU(True),
            nn.Linear(1024, 64 * 64 * 3),
            nn.Tanh()
        )

    def forward(self, input):
        output = self.main(input)
        return output.view(-1, 3, 64, 64)

# Discriminator(判別モデル)
class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()
        self.main = nn.Sequential(
            nn.Linear(64 * 64 * 3, 1024),
            nn.ReLU(True),
            nn.Linear(1024, 512),
            nn.ReLU(True),
            nn.Linear(512, 256),
            nn.ReLU(True),
            nn.Linear(256, 1),
            nn.Sigmoid()
        )

    def forward(self, input):
        input_flat = input.view(-1, 64 * 64 * 3)
        return self.main(input_flat)

# モデルのインスタンス化
G = Generator()
D = Discriminator()

# ロス関数とオプティマイザ
criterion = nn.BCELoss()
optimizerD = optim.Adam(D.parameters(), lr=0.0002)
optimizerG = optim.Adam(G.parameters(), lr=0.0002)

# ランダムノイズ生成関数
def generate_noise(batch_size):
    return torch.randn(batch_size, 100)

# トレーニングループ
num_epochs = 50
for epoch in range(num_epochs):
    for i, (real_images, _) in enumerate(tqdm(dataloader)):
        batch_size = real_images.size(0)

        # 本物の画像のラベルは1、偽物の画像のラベルは0
        real_labels = torch.ones(batch_size, 1)
        fake_labels = torch.zeros(batch_size, 1)

        # Discriminatorの学習
        optimizerD.zero_grad()
        outputs = D(real_images)
        real_loss = criterion(outputs, real_labels)

        noise = generate_noise(batch_size)
        fake_images = G(noise)
        outputs = D(fake_images.detach())
        fake_loss = criterion(outputs, fake_labels)

        d_loss = real_loss + fake_loss
        d_loss.backward()
        optimizerD.step()

        # Generatorの学習
        optimizerG.zero_grad()
        outputs = D(fake_images)
        g_loss = criterion(outputs, real_labels)  # 生成画像を本物と認識させたい
        g_loss.backward()
        optimizerG.step()

    print(f'Epoch [{epoch+1}/{num_epochs}] | d_loss: {d_loss.item()} | g_loss: {g_loss.item()}')

    # 生成された画像を表示
    if (epoch + 1) % 10 == 0:
        fake_images = G(generate_noise(64)).detach().cpu()
        plt.imshow(fake_images[0].permute(1, 2, 0) * 0.5 + 0.5)
       

簡単な画像生成AI python

import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image  # 画像保存のための関数
import os  # ファイルの保存先を指定するためのライブラリ

# VAEのエンコーダーとデコーダー
class VAE(nn.Module):
    def __init__(self, input_dim=784, hidden_dim=400, latent_dim=20):
        super(VAE, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc21 = nn.Linear(hidden_dim, latent_dim)
        self.fc22 = nn.Linear(hidden_dim, latent_dim)
        self.fc3 = nn.Linear(latent_dim, hidden_dim)
        self.fc4 = nn.Linear(hidden_dim, input_dim)

    def encode(self, x):
        h1 = torch.relu(self.fc1(x))
        return self.fc21(h1), self.fc22(h1)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std

    def decode(self, z):
        h3 = torch.relu(self.fc3(z))
        return torch.sigmoid(self.fc4(h3))

    def forward(self, x):
        mu, logvar = self.encode(x.view(-1, 784))
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

# VAEの損失関数
def loss_function(recon_x, x, mu, logvar):
    BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + KLD

# モデルの定義とデータローダーの準備
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
vae = VAE().to(device)
optimizer = optim.Adam(vae.parameters(), lr=1e-3)

transform = transforms.ToTensor()
train_dataset = datasets.MNIST('.', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)

# トレーニングループ
vae.train()
for epoch in range(10):  # 10エポックで学習
    train_loss = 0
    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.to(device)
        optimizer.zero_grad()
        recon_batch, mu, logvar = vae(data)
        loss = loss_function(recon_batch, data, mu, logvar)
        loss.backward()
        train_loss += loss.item()
        optimizer.step()
    
    print(f'Epoch {epoch + 1}, Loss: {train_loss / len(train_loader.dataset)}')

# 学習したモデルで画像生成
vae.eval()
with torch.no_grad():
    z = torch.randn(64, 20).to(device)
    sample = vae.decode(z).cpu()
    sample = sample.view(64, 1, 28, 28)  # 28x28の画像サイズに変換 (MNISTデータのフォーマット)
    
    # 保存先ディレクトリを指定
    os.makedirs('generated_images', exist_ok=True)
    save_image(sample, 'generated_images/sample.png')

    print("画像生成完了: 'generated_images/sample.png' に保存されました")

python AIChatBOT

import re
import datetime

class Chatbot:
    def __init__(self):
        self.context = {}
        self.history = []
        self.user_name = None
        self.current_intent = None  # 現在の意図を保持
        self.emotion_state = "neutral"  # ユーザーの感情状態
        self.long_term_memory = {}  # ユーザーの好みなどを記憶する

    # コンテキストと履歴を更新
    def update_context(self, key, value):
        self.context[key] = value

    def add_to_history(self, user_input, bot_response):
        self.history.append({"user": user_input, "bot": bot_response})

    # 感情を分析
    def analyze_emotion(self, user_input):
        if re.search(r"疲れた|悲しい", user_input):
            return "sad"
        elif re.search(r"嬉しい|楽しい", user_input):
            return "happy"
        else:
            return "neutral"

    # 意図の認識
    def intent_recognition(self, user_input):
        if re.search(r"こんにちは|おはよう", user_input):
            return "greeting"
        elif re.search(r"名前は|あなたは誰", user_input):
            return "identity"
        elif re.search(r"ありがとう", user_input):
            return "thanks"
        elif re.search(r"天気|天候", user_input):
            return "weather"
        elif re.search(r"日付|時間", user_input):
            return "time"
        elif re.search(r"さようなら|バイバイ", user_input):
            return "farewell"
        elif re.search(r"趣味", user_input):
            return "hobby"
        elif re.search(r"タスク|予定", user_input):
            return "task_management"
        else:
            return "unknown"

    # 意図に応じた応答生成
    def handle_intent(self, intent, user_input):
        if intent == "greeting":
            return self.greet_user()
        elif intent == "identity":
            return self.ask_for_name()
        elif intent == "thanks":
            return "どういたしまして!"
        elif intent == "weather":
            return self.get_weather()
        elif intent == "time":
            return self.get_time()
        elif intent == "farewell":
            return "さようなら!またお会いしましょう。"
        elif intent == "hobby":
            return self.ask_hobby()
        elif intent == "task_management":
            return self.manage_task()
        else:
            return "すみません、よくわかりません。もう一度お願いします。"

    # 挨拶応答
    def greet_user(self):
        if self.user_name:
            return f"こんにちは、{self.user_name}さん!今日はどうされましたか?"
        else:
            return "こんにちは!お名前を教えていただけますか?"

    # 名前を聞く
    def ask_for_name(self):
        if not self.user_name:
            self.current_intent = "ask_name"
            return "私はあなたの名前をまだ聞いていませんね。教えていただけますか?"
        else:
            return f"あなたのお名前は{self.user_name}ですね!"

    # 趣味について聞く
    def ask_hobby(self):
        if "hobby" not in self.long_term_memory:
            self.current_intent = "ask_hobby"
            return "趣味は何ですか?"
        else:
            hobby = self.long_term_memory['hobby']
            return f"以前おっしゃった趣味は{hobby}ですね!"

    # タスク管理(例: カレンダーに予定を追加)
    def manage_task(self):
        self.current_intent = "task_management"
        return "新しい予定を追加したいのですか?詳細を教えてください。"

    # 天気情報の取得(仮想)
    def get_weather(self):
        return "今日は晴れで、気温は22度です。"

    # 日付・時間を取得
    def get_time(self):
        now = datetime.datetime.now()
        return f"今は{now.strftime('%Y年%m月%d日 %H:%M:%S')}です。"

    # 応答を感情に基づいて調整
    def adjust_response_by_emotion(self, response):
        if self.emotion_state == "sad":
            return f"元気出してくださいね。{response}"
        elif self.emotion_state == "happy":
            return f"素晴らしいですね!{response}"
        else:
            return response

    # 名前を更新
    def update_name(self, user_input):
        self.user_name = user_input
        self.long_term_memory['name'] = user_input

    # 趣味を保存
    def update_hobby(self, user_input):
        self.long_term_memory['hobby'] = user_input

    # 応答のメインロジック
    def chatbot_response(self, user_input):
        if self.current_intent == "ask_name":
            self.update_name(user_input)
            return f"お名前は{self.user_name}さんですね!よろしくお願いします!"
        elif self.current_intent == "ask_hobby":
            self.update_hobby(user_input)
            return f"{self.user_name}さんの趣味は{user_input}ですね!"

        # 感情分析
        self.emotion_state = self.analyze_emotion(user_input)

        # 意図解析
        intent = self.intent_recognition(user_input)

        # 応答生成
        response = self.handle_intent(intent, user_input)

        # コンテキストと履歴の更新
        self.add_to_history(user_input, response)
        return self.adjust_response_by_emotion(response)

# チャットボットを実行
def run_chatbot():
    chatbot = Chatbot()
    
    # 初回挨拶
    print("ボット: こんにちは!お名前を教えてください。")
    
    while True:
        user_input = input("あなた: ")
        
        if user_input == "終了":
            print("チャットを終了します。")
            break
        
        bot_response = chatbot.chatbot_response(user_input)
        print("ボット: " + bot_response)

# チャットボットを実行
run_chatbot()

Solve the Two Sum problem in Python

Solve the Two Sum problem in Python

回答

Certainly, I’ll provide a solution to the Two Sum problem in Python. This problem is a common interview question where you’re given an array of integers and a target sum, and you need to find two numbers in the array that add up to the target.

Here’s a step-by-step approach:

  1. Use a Hash Map: This approach allows for O(n) time complexity, where n is the number of elements in the array.
  2. Iterate Through the Array: For each number, calculate what the other number should be to reach the target sum.
  3. Check if the Complement Exists: If the complement exists in the hash map, return the indices of both numbers.

Here’s the implementation:

python

def two_sum(nums, target):
    # Dictionary to store the number and its index
    num_dict = {}
    
    # Iterate through the list
    for i, num in enumerate(nums):
        # Calculate the complement
        complement = target - num
        
        # If the complement exists in the dictionary, return the indices
        if complement in num_dict:
            return [num_dict[complement], i]
        
        # If not, add the current number and its index to the dictionary
        num_dict[num] = i
    
    # If no solution is found, return an empty list or raise an exception
    return []  # or raise ValueError("No two sum solution")

# Example usage
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result)  # Should print [0, 1] because nums[0] + nums[1] == 9

Explanation:

  • We use a dictionary (num_dict) to keep track of numbers we’ve seen and their indices.
  • As we iterate through the list:
    • We calculate what number, when added to the current number, would give us the target.
    • If this number exists in our dictionary, we’ve found our pair, and we return their indices.
    • If not, we add the current number and its index to the dictionary.

This solution ensures that we only traverse the list once, making it efficient with a time complexity of O(n). The space complexity is also O(n) in the worst case where all numbers are unique.

python AI

プロジェクトのファイル構成

chatbot_project/

├── app.py
├── chatbot.db (自動生成されます)
├── requirements.txt
├── templates/
│ └── index.html
└── static/
└── css/
└── style.css

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AIチャットボット</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <style>
        .chat-container {
            max-width: 700px;
            margin: 50px auto;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .messages {
            height: 500px;
            overflow-y: auto;
            border-bottom: 1px solid #ddd;
            padding: 20px;
        }
        .message {
            margin: 10px 0;
        }
        .user .message-content {
            background: #007bff;
            color: #fff;
            border-radius: 15px 15px 0 15px;
            padding: 10px 15px;
            display: inline-block;
        }
        .bot .message-content {
            background: #f1f1f1;
            border-radius: 15px 15px 15px 0;
            padding: 10px 15px;
            display: inline-block;
        }
        .input-group {
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="messages" id="messages"></div>
        <div class="input-group">
            <input type="text" id="userInput" class="form-control" placeholder="メッセージを入力">
            <div class="input-group-append">
                <button class="btn btn-primary" onclick="sendMessage()">送信</button>
            </div>
        </div>
    </div>

    <script>
        async function sendMessage() {
            const userInput = document.getElementById('userInput').value;
            if (userInput.trim() === "") return;

            displayMessage(userInput, 'user');
            document.getElementById('userInput').value = "";

            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: userInput })
                });

                const data = await response.json();
                displayMessage(data.reply, 'bot');
            } catch (error) {
                displayMessage('エラーが発生しました。', 'bot');
            }
        }

        function displayMessage(message, sender) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}`;
            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.textContent = message;
            messageDiv.appendChild(messageContent);
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
    </script>
</body>
</html>

style.css

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}

app.py

from flask import Flask, request, jsonify, render_template
import nltk
from nltk.chat.util import Chat, reflections
import spacy
import sqlite3
import os

app = Flask(__name__)
nlp = spacy.load('en_core_web_sm')

pairs = [
    [
        r"こんにちは|やあ|おはよう",
        ["こんにちは!", "やあ!", "おはようございます!"]
    ],
    [
        r"あなたの名前は何ですか?",
        ["私はAIチャットボットです。", "私の名前はまだありません。"]
    ],
    [
        r"さようなら|バイバイ",
        ["さようなら!", "またね!"]
    ]
]

chat = Chat(pairs, reflections)

# SQLiteデータベース接続
def get_db_connection():
    conn = sqlite3.connect('chatbot.db')
    conn.row_factory = sqlite3.Row
    return conn

with get_db_connection() as conn:
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS messages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_message TEXT,
            bot_response TEXT
        )
    ''')
    conn.commit()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/chat', methods=['POST'])
def chat_response():
    user_message = request.json.get('message')
    response = chat.respond(user_message)

    if response is None:
        response = advanced_nlp_response(user_message)

    with get_db_connection() as conn:
        c = conn.cursor()
        c.execute('INSERT INTO messages (user_message, bot_response) VALUES (?, ?)', (user_message, response))
        conn.commit()

    return jsonify({'reply': response})

def advanced_nlp_response(user_message):
    doc = nlp(user_message)
    if doc.ents:
        entities = [ent.text for ent in doc.ents]
        return f"あなたのメッセージには次のエンティティが含まれています: {', '.join(entities)}"
    else:
        return "ごめんなさい、理解できませんでした。"

@app.route('/history', methods=['GET'])
def chat_history():
    with get_db_connection() as conn:
        c = conn.cursor()
        c.execute('SELECT * FROM messages')
        rows = c.fetchall()
        history = [{"user_message": row["user_message"], "bot_response": row["bot_response"]} for row in rows]
    return jsonify(history)

if __name__ == '__main__':
    nltk.download('punkt')
    app.run(debug=True)

python プログラミング言語

import re

# トークナイザー
def tokenize(code):
    token_specification = [
        ('NUMBER',   r'\d+'),          # 整数
        ('ID',       r'[A-Za-z_]\w*'), # 識別子
        ('ASSIGN',   r'='),            # 代入演算子
        ('END',      r';'),            # 文の終わり
        ('OP',       r'[+\-*/]'),      # 演算子
        ('NEWLINE',  r'\n'),           # 改行
        ('SKIP',     r'[ \t]'),        # 空白とタブ
        ('MISMATCH', r'.'),            # 一致しない文字
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
    get_token = re.compile(tok_regex).finditer
    tokens = []
    for mo in get_token(code):
        kind = mo.lastgroup
        value = mo.group()
        if kind == 'NUMBER':
            value = int(value)
        elif kind == 'ID' and value in {'if', 'while', 'def'}:
            kind = value.upper()
        elif kind == 'SKIP':
            continue
        elif kind == 'NEWLINE':
            value = '\n'
        elif kind == 'MISMATCH':
            raise RuntimeError(f'{value} unexpected on line {code}')
        tokens.append((kind, value))
    return tokens

# パーサークラス
class Parser:
    def __init__(self, tokens):
        self.tokens = tokens
        self.pos = 0

    def parse(self):
        statements = []
        while self.pos < len(self.tokens):
            statement = self.statement()
            if statement:
                statements.append(statement)
        return statements

    def statement(self):
        if self.pos >= len(self.tokens):
            return None
        token = self.tokens[self.pos]
        if token[0] == 'ID' and self.pos + 1 < len(self.tokens) and self.tokens[self.pos + 1][0] == 'ASSIGN':
            return self.assignment()
        elif token[0] in {'ID', 'NUMBER'} or (token[0] == 'OP' and token[1] == '-'):
            return self.expression()
        else:
            raise SyntaxError(f'Unexpected token: {token}')

    def assignment(self):
        id_token = self.tokens[self.pos]
        self.pos += 1  # skip ID
        self.pos += 1  # skip ASSIGN
        expr = self.expression()
        self.expect('END')
        return ('assign', id_token[1], expr)

    def expression(self):
        term = self.term()
        while self.pos < len(self.tokens) and self.tokens[self.pos][0] == 'OP':
            op = self.tokens[self.pos]
            self.pos += 1
            term = (op[1], term, self.term())
        return term

    def term(self):
        token = self.tokens[self.pos]
        if token[0] == 'NUMBER':
            self.pos += 1
            return token[1]
        elif token[0] == 'ID':
            self.pos += 1
            return ('var', token[1])
        else:
            raise SyntaxError(f'Unexpected token: {token}')

    def expect(self, kind):
        if self.pos < len(self.tokens) and self.tokens[self.pos][0] == kind:
            self.pos += 1
        else:
            raise SyntaxError(f'Expected {kind}')

# インタプリタクラス
class Interpreter:
    def __init__(self):
        self.variables = {}

    def evaluate(self, node):
        if isinstance(node, int):
            return node
        elif isinstance(node, tuple):
            if node[0] == 'assign':
                self.variables[node[1]] = self.evaluate(node[2])
                return self.variables[node[1]]
            elif node[0] == 'var':
                if node[1] in self.variables:
                    return self.variables[node[1]]
                else:
                    raise NameError(f"Variable '{node[1]}' is not defined")
            else:
                left = self.evaluate(node[1])
                right = self.evaluate(node[2])
                if node[0] == '+':
                    return left + right
                elif node[0] == '-':
                    return left - right
                elif node[0] == '*':
                    return left * right
                elif node[0] == '/':
                    return left / right
        return None

# REPL (Read-Eval-Print Loop)
def repl():
    interpreter = Interpreter()
    while True:
        try:
            code = input('>>> ')
            if code == 'exit':
                break
            tokens = tokenize(code)
            parser = Parser(tokens)
            tree = parser.parse()
            for statement in tree:
                result = interpreter.evaluate(statement)
                if result is not None:
                    print(result)
        except Exception as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    repl()

python WEBブラウザ

import sys
import os
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QWidget, QTabWidget, QAction, QMenuBar, QMenu, QListWidget, QInputDialog, QMessageBox, QFileDialog, QToolBar)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEngineDownloadItem
from PyQt5.QtCore import QUrl, QTimer, Qt

class Browser(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Advanced Browser')
        self.setGeometry(100, 100, 1200, 800)
        
        self.bookmarks = []
        self.history = []
        self.home_page = 'http://www.google.com'
        self.auto_browse_url = ''
        self.auto_browse_interval = 60
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.auto_browse)

        self.load_settings()

        self.tab_widget = QTabWidget()
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.tabBarDoubleClicked.connect(self.add_new_tab)
        self.tab_widget.currentChanged.connect(self.update_url_bar)
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested.connect(self.close_current_tab)

        self.setCentralWidget(self.tab_widget)
        self.status = QLineEdit()
        self.status.setReadOnly(True)
        self.statusBar().addPermanentWidget(self.status)

        navtb = QToolBar("Navigation")
        self.addToolBar(navtb)

        self.url_bar = QLineEdit()
        self.url_bar.returnPressed.connect(self.navigate_to_url)

        self.back_button = QPushButton('<')
        self.back_button.clicked.connect(lambda: self.tab_widget.currentWidget().back())

        self.forward_button = QPushButton('>')
        self.forward_button.clicked.connect(lambda: self.tab_widget.currentWidget().forward())

        self.reload_button = QPushButton('R')
        self.reload_button.clicked.connect(lambda: self.tab_widget.currentWidget().reload())

        self.add_tab_button = QPushButton('+')
        self.add_tab_button.clicked.connect(self.add_new_tab)

        self.auto_browse_button = QPushButton('Auto Browse')
        self.auto_browse_button.clicked.connect(self.toggle_auto_browse)

        navtb.addWidget(self.back_button)
        navtb.addWidget(self.forward_button)
        navtb.addWidget(self.reload_button)
        navtb.addWidget(self.url_bar)
        navtb.addWidget(self.add_tab_button)
        navtb.addWidget(self.auto_browse_button)

        self.menu_bar = QMenuBar()
        self.setMenuBar(self.menu_bar)

        self.file_menu = QMenu("&File", self)
        self.menu_bar.addMenu(self.file_menu)

        self.bookmark_menu = QMenu("&Bookmarks", self)
        self.menu_bar.addMenu(self.bookmark_menu)
        self.bookmark_menu.addAction("Add Bookmark", self.add_bookmark)
        self.bookmark_menu.addAction("Show Bookmarks", self.show_bookmarks)

        self.history_menu = QMenu("&History", self)
        self.menu_bar.addMenu(self.history_menu)
        self.history_menu.addAction("Show History", self.show_history)
        
        self.settings_menu = QMenu("&Settings", self)
        self.menu_bar.addMenu(self.settings_menu)
        self.settings_menu.addAction("Set Home Page", self.set_home_page)
        self.settings_menu.addAction("Set Auto Browse", self.set_auto_browse)

        self.add_new_tab(QUrl(self.home_page), "Home")

    def add_new_tab(self, qurl=None, label="New Tab"):
        if qurl is None:
            qurl = QUrl(self.home_page)

        browser = QWebEngineView()
        browser.setUrl(qurl)
        i = self.tab_widget.addTab(browser, label)
        self.tab_widget.setCurrentIndex(i)

        browser.urlChanged.connect(lambda qurl, browser=browser: self.update_url(qurl, browser))
        browser.loadFinished.connect(lambda _, i=i, browser=browser: self.tab_widget.setTabText(i, browser.page().title()))
        browser.page().profile().downloadRequested.connect(self.download_requested)

    def update_url(self, qurl, browser=None):
        if browser != self.tab_widget.currentWidget():
            return
        self.url_bar.setText(qurl.toString())
        self.status.setText(qurl.toString())
        self.history.append(qurl.toString())

    def navigate_to_url(self):
        qurl = QUrl(self.url_bar.text())
        self.tab_widget.currentWidget().setUrl(qurl)

    def update_url_bar(self, i):
        qurl = self.tab_widget.currentWidget().url()
        self.url_bar.setText(qurl.toString())
        self.status.setText(qurl.toString())

    def close_current_tab(self, i):
        if self.tab_widget.count() < 2:
            return
        self.tab_widget.removeTab(i)

    def add_bookmark(self):
        url = self.url_bar.text()
        if url and url not in self.bookmarks:
            self.bookmarks.append(url)
            QMessageBox.information(self, "Bookmark Added", "Bookmark has been added.")
            self.save_settings()

    def show_bookmarks(self):
        dlg = QInputDialog(self)
        dlg.setLabelText("Bookmarks:")
        dlg.setComboBoxItems(self.bookmarks)
        dlg.exec_()

    def show_history(self):
        dlg = QInputDialog(self)
        dlg.setLabelText("History:")
        dlg.setComboBoxItems(self.history)
        dlg.exec_()

    def set_home_page(self):
        url, ok = QInputDialog.getText(self, "Set Home Page", "Enter URL:")
        if ok and url:
            self.home_page = url
            self.save_settings()

    def set_auto_browse(self):
        url, ok1 = QInputDialog.getText(self, "Set Auto Browse URL", "Enter URL:")
        if ok1 and url:
            interval, ok2 = QInputDialog.getInt(self, "Set Auto Browse Interval", "Enter Interval (seconds):", min=1)
            if ok2:
                self.auto_browse_url = url
                self.auto_browse_interval = interval
                self.save_settings()

    def toggle_auto_browse(self):
        if self.timer.isActive():
            self.timer.stop()
            self.auto_browse_button.setText("Auto Browse")
        else:
            self.timer.start(self.auto_browse_interval * 1000)
            self.auto_browse_button.setText("Stop Auto Browse")

    def auto_browse(self):
        if self.auto_browse_url:
            self.tab_widget.currentWidget().setUrl(QUrl(self.auto_browse_url))

    def download_requested(self, download):
        path, _ = QFileDialog.getSaveFileName(self, "Save File", download.path())
        if path:
            download.setPath(path)
            download.accept()

    def load_settings(self):
        if os.path.exists('browser_settings.json'):
            with open('browser_settings.json', 'r') as f:
                settings = json.load(f)
                self.bookmarks = settings.get('bookmarks', [])
                self.history = settings.get('history', [])
                self.home_page = settings.get('home_page', 'http://www.google.com')
                self.auto_browse_url = settings.get('auto_browse_url', '')
                self.auto_browse_interval = settings.get('auto_browse_interval', 60)

    def save_settings(self):
        settings = {
            'bookmarks': self.bookmarks,
            'history': self.history,
            'home_page': self.home_page,
            'auto_browse_url': self.auto_browse_url,
            'auto_browse_interval': self.auto_browse_interval
        }
        with open('browser_settings.json', 'w') as f:
            json.dump(settings, f)

app = QApplication(sys.argv)
app.setApplicationName("Advanced Browser")
window = Browser()
window.show()
sys.exit(app.exec_())

python バケモン

import random

class Bakemon:
    def __init__(self, name, hp, attack):
        self.name = name
        self.hp = hp
        self.attack = attack

    def is_alive(self):
        return self.hp > 0

    def take_damage(self, damage):
        self.hp -= damage
        if self.hp < 0:
            self.hp = 0

    def attack_opponent(self, opponent):
        damage = random.randint(1, self.attack)
        opponent.take_damage(damage)
        return damage

def create_bakemon():
    bakemon_list = [
        Bakemon("Bakachu", 50, 10),
        Bakemon("Charabak", 60, 12),
        Bakemon("Bakasaur", 55, 11),
        Bakemon("Squirtlemon", 50, 10)
    ]
    return bakemon_list

def choose_bakemon(bakemon_list):
    print("Choose your Bakemon:")
    for idx, bakemon in enumerate(bakemon_list):
        print(f"{idx + 1}. {bakemon.name} (HP: {bakemon.hp}, Attack: {bakemon.attack})")
    choice = int(input("Enter the number of your choice: ")) - 1
    return bakemon_list[choice]

def battle(player_bakemon, enemy_bakemon):
    print(f"A wild {enemy_bakemon.name} appeared!")
    while player_bakemon.is_alive() and enemy_bakemon.is_alive():
        print(f"\n{player_bakemon.name} (HP: {player_bakemon.hp}) vs {enemy_bakemon.name} (HP: {enemy_bakemon.hp})")
        action = input("Do you want to attack (a) or run (r)? ").lower()
        if action == 'a':
            damage = player_bakemon.attack_opponent(enemy_bakemon)
            print(f"{player_bakemon.name} dealt {damage} damage to {enemy_bakemon.name}!")
            if enemy_bakemon.is_alive():
                damage = enemy_bakemon.attack_opponent(player_bakemon)
                print(f"{enemy_bakemon.name} dealt {damage} damage to {player_bakemon.name}!")
            else:
                print(f"{enemy_bakemon.name} is defeated!")
                break
        elif action == 'r':
            print("You ran away!")
            break
        else:
            print("Invalid action. Please choose again.")
    
    if not player_bakemon.is_alive():
        print(f"{player_bakemon.name} is defeated! Game over.")
        return False
    return True

def main():
    print("Welcome to the Bakemon game!")
    bakemon_list = create_bakemon()
    player_bakemon = choose_bakemon(bakemon_list)
    
    while True:
        enemy_bakemon = random.choice(bakemon_list)
        if enemy_bakemon == player_bakemon:
            continue
        if not battle(player_bakemon, enemy_bakemon):
            break
        play_again = input("Do you want to battle again? (y/n): ").lower()
        if play_again != 'y':
            print("Thanks for playing! Goodbye.")
            break

if __name__ == "__main__":
    main()

python 簡単な会話モデルの構築

from nltk.chat.util import Chat, reflections

pairs = [
[‘こんにちは’, [‘こんにちは!’, ‘どうもこんにちは!’]],
[‘元気ですか?’, [‘はい、元気です!’, ‘お尋ねいただきありがとうございます。’]],
[‘名前は何ですか?’, [‘私はチャットボットです。’, ‘私の名前はチャットボットです。’]],
[‘さようなら’, [‘さようなら!またね。’, ‘良い一日を!’]],
]

chatbot = Chat(pairs, reflections)

def chatbot_response(user_input):
return chatbot.respond(user_input)

ユーザーとの対話

while True:
user_input = input(“あなた: “)
response = chatbot_response(user_input)
print(“チャットボット:”, response)