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
GPT-2 ChatBot
import nltk
from transformers import pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import numpy as np
import spacy
# nltkのセットアップ(初回のみ)
nltk.download('punkt')
# spaCyのセットアップ
nlp = spacy.load("en_core_web_sm")
# サンプルデータ(インテントとそのサンプル文)
training_sentences = [
"Hello", "Hi", "Hey", "Good morning", "Good evening",
"How are you?", "What's up?", "How's it going?",
"Bye", "Goodbye", "See you later", "Take care",
"Thank you", "Thanks", "I appreciate it",
"What's your name?", "Who are you?",
"What can you do?", "Tell me a joke", "Make me laugh",
"What's the weather like?", "How's the weather?",
"Book a flight", "I need to book a flight", "Can you book a flight for me?"
]
intents = [
"greeting", "greeting", "greeting", "greeting", "greeting",
"how_are_you", "how_are_you", "how_are_you",
"goodbye", "goodbye", "goodbye", "goodbye",
"thanks", "thanks", "thanks",
"name", "name",
"capabilities", "joke", "joke",
"weather", "weather",
"book_flight", "book_flight", "book_flight"
]
# 特徴抽出器と分類器のセットアップ
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(training_sentences)
classifier = LogisticRegression()
classifier.fit(X, intents)
# GPT-2 を使用したテキスト生成パイプラインの作成
chatbot = pipeline("text-generation", model="gpt2")
# インテントに基づく応答
responses = {
"greeting": ["Hello! How can I help you?", "Hi there! What can I do for you?"],
"how_are_you": ["I'm just a bot, but I'm here to help you!", "I'm fine, thank you! How can I assist you today?"],
"goodbye": ["Goodbye! Have a great day!", "See you later!"],
"thanks": ["You're welcome!", "No problem!"],
"name": ["I am your friendly chatbot.", "I'm an AI created to assist you."],
"capabilities": ["I can chat with you and help answer your questions!", "I'm here to assist you with various tasks."],
"joke": ["Why did the scarecrow win an award? Because he was outstanding in his field!"],
"weather": ["The weather is nice today!", "It's a bit cloudy, but still good."],
"book_flight": ["Sure, I can help you with that. Where would you like to go?"]
}
# 未知のインテントに対するエラーレスポンス
default_responses = ["I'm not sure I understand. Can you please rephrase?", "Sorry, I don't have an answer for that."]
# インテント認識
def get_intent(user_input):
X_test = vectorizer.transform([user_input])
intent = classifier.predict(X_test)[0]
return intent
# エンティティ認識
def get_entities(user_input):
doc = nlp(user_input)
entities = {ent.label_: ent.text for ent in doc.ents}
return entities
# 応答生成
def get_response(user_input):
intent = get_intent(user_input)
entities = get_entities(user_input)
if intent in responses:
response = np.random.choice(responses[intent])
if intent == "book_flight" and "GPE" in entities:
response = f"Sure, I can help you book a flight to {entities['GPE']}. When would you like to travel?"
return response
else:
response = chatbot(user_input, max_length=50, num_return_sequences=1)
return response[0]['generated_text']
# メイン関数
def main():
print("Chatbot: Hello! How can I help you today? (Type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye!")
break
response = get_response(user_input)
print(f"Chatbot: {response}")
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)
python 戻り値
def add(a, b):
return a+b
c = add(1,2)
print(c)
python chatGPT2-AI
chatGPT-2.py
from flask import Flask, render_template, request, redirect, url_for
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import wikipedia
app = Flask(__name__)
# GPT-2のトークナイザーとモデルをロード
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate_text():
# ユーザーからの入力を取得
prompt_text = request.form['prompt']
try:
# Wikipediaからテキストを取得
wikipedia_text = wikipedia.summary(prompt_text)
# テキストの生成
inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
# 生成されたテキストをデコードしてHTMLコードに組み込む
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# 生成されたテキストとWikipediaのテキストと共にHTMLを返す
return render_template('index.html', prompt_text=prompt_text, generated_text=generated_text, wikipedia_text=wikipedia_text)
except wikipedia.exceptions.DisambiguationError as e:
# 曖昧性がある場合は、候補のリストを表示
options = e.options
return render_template('disambiguation.html', options=options)
except wikipedia.exceptions.PageError:
wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
return render_template('index.html', prompt_text=prompt_text, wikipedia_text=wikipedia_text)
@app.route('/generate_with_option/<option>', methods=['GET'])
def generate_with_option(option):
try:
# Wikipediaからテキストを取得
wikipedia_text = wikipedia.summary(option)
# テキストの生成
inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
# 生成されたテキストをデコードしてHTMLコードに組み込む
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# 生成されたテキストとWikipediaのテキストと共にHTMLを返す
return render_template('index.html', prompt_text=option, generated_text=generated_text, wikipedia_text=wikipedia_text)
except wikipedia.exceptions.PageError:
wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
return render_template('index.html', prompt_text=option, wikipedia_text=wikipedia_text)
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generate Text</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header {
text-align: center;
margin-top: 50px;
}
main {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.form-section, .response-section, .wikipedia-section {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
margin-bottom: 20px;
}
.prompt-form {
max-width: 100%;
}
label {
font-weight: bold;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
.generated-text {
margin-top: 20px;
}
.tweet-link {
display: block;
margin-top: 10px;
text-align: center;
}
footer {
text-align: center;
margin-top: 50px;
}
</style>
</head>
<body>
<header>
<h1>Generate Text</h1>
</header>
<main>
<section class="form-section">
<form action="/generate" method="POST" class="prompt-form">
<label for="prompt">Enter your prompt:</label><br>
<input type="text" id="prompt" name="prompt" placeholder="Enter your prompt..."><br><br>
<button type="submit">Generate</button>
</form>
</section>
<!-- 生成されたテキストを表示 -->
{% if generated_text %}
<section class="response-section">
<div class="response">
<h2>Generated Text:</h2>
<p class="generated-text">{{ generated_text }}</p>
<a href="https://twitter.com/intent/tweet?text={{ generated_text }}" class="tweet-link">Tweet</a>
</div>
</section>
{% endif %}
<!-- Wikipediaからの関連情報を表示 -->
{% if wikipedia_text %}
<section class="wikipedia-section">
<div class="wikipedia-info">
<h2>Wikipedia Info:</h2>
<p>{{ wikipedia_text }}</p>
</div>
</section>
{% endif %}
<!-- 保存ボタン -->
<button id="saveButton">Save Generated Text</button>
</main>
<footer>
<p>© 2024 Generate Text App</p>
</footer>
<script>
// 保存ボタンがクリックされたときの処理
document.getElementById('saveButton').addEventListener('click', function() {
// 生成されたテキストを取得
var generatedText = document.querySelector('.generated-text').innerText;
// テキストをダウンロード用にBlobに変換
var blob = new Blob([generatedText], { type: 'text/plain' });
// BlobをURLに変換
var url = window.URL.createObjectURL(blob);
// ダウンロード用のリンクを作成してクリック
var a = document.createElement('a');
a.href = url;
a.download = 'generated_text.txt';
document.body.appendChild(a);
a.click();
// 不要なURLを解放
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});
</script>
</body>
</html>
今回はテキストデータを保存できるようにしました
GPT-2とWikipediaを使って生成するAI
GPT-2.py
from flask import Flask, render_template, request, redirect, url_for
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import wikipedia
app = Flask(__name__)
# GPT-2のトークナイザーとモデルをロード
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate_text():
# ユーザーからの入力を取得
prompt_text = request.form['prompt']
try:
# Wikipediaからテキストを取得
wikipedia_text = wikipedia.summary(prompt_text)
# テキストの生成
inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
# 生成されたテキストをデコードしてHTMLコードに組み込む
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# 生成されたテキストとWikipediaのテキストと共にHTMLを返す
return render_template('index.html', prompt_text=prompt_text, generated_text=generated_text, wikipedia_text=wikipedia_text)
except wikipedia.exceptions.DisambiguationError as e:
# 曖昧性がある場合は、候補のリストを表示
options = e.options
return render_template('disambiguation.html', options=options)
except wikipedia.exceptions.PageError:
wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
return render_template('index.html', prompt_text=prompt_text, wikipedia_text=wikipedia_text)
@app.route('/generate_with_option/<option>', methods=['GET'])
def generate_with_option(option):
try:
# Wikipediaからテキストを取得
wikipedia_text = wikipedia.summary(option)
# テキストの生成
inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
# 生成されたテキストをデコードしてHTMLコードに組み込む
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# 生成されたテキストとWikipediaのテキストと共にHTMLを返す
return render_template('index.html', prompt_text=option, generated_text=generated_text, wikipedia_text=wikipedia_text)
except wikipedia.exceptions.PageError:
wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
return render_template('index.html', prompt_text=option, wikipedia_text=wikipedia_text)
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generate Text</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
h1 {
text-align: center;
margin-top: 50px;
}
form {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
label {
font-weight: bold;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
.response {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.generated-text {
margin-top: 20px;
}
.tweet-link {
display: block;
margin-top: 10px;
text-align: center;
}
</style>
</head>
<body>
<h1>Generate Text</h1>
<form action="/generate" method="POST">
<label for="prompt">Enter your prompt:</label><br>
<input type="text" id="prompt" name="prompt"><br><br>
<button type="submit">Generate</button>
</form>
<!-- 生成されたテキストを表示 -->
{% if generated_text %}
<div class="response">
<h2>Generated Text:</h2>
<p class="generated-text">{{ generated_text }}</p>
<a href="https://twitter.com/intent/tweet?text={{ generated_text }}" class="tweet-link" target="_blank">Tweet</a>
</div>
{% endif %}
</body>
</html>
templates/disambiguation.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disambiguation Page</title>
</head>
<body>
<h1>Disambiguation</h1>
<p>Multiple meanings were found for the provided prompt. Please select the intended meaning:</p>
<ul>
{% for option in options %}
<li><a href="{{ url_for('generate_with_option', option=option) }}">{{ option }}</a></li>
{% endfor %}
</ul>
</body>
</html>
python タスク
import os
import json
from datetime import datetime
class Task:
def __init__(self, description, deadline=None, completed=False):
self.description = description
self.deadline = deadline
self.completed = completed
def to_dict(self):
return {
"description": self.description,
"deadline": self.deadline.strftime("%Y-%m-%d %H:%M") if self.deadline else None,
"completed": self.completed
}
@classmethod
def from_dict(cls, task_dict):
deadline_str = task_dict.get("deadline")
deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
return cls(task_dict["description"], deadline, task_dict["completed"])
class TaskList:
def __init__(self, filename):
self.filename = filename
self.tasks = []
self.load_tasks()
def load_tasks(self):
if os.path.exists(self.filename):
with open(self.filename, 'r') as file:
task_data = json.load(file)
self.tasks = [Task.from_dict(task_dict) for task_dict in task_data]
def save_tasks(self):
with open(self.filename, 'w') as file:
task_data = [task.to_dict() for task in self.tasks]
json.dump(task_data, file, indent=4)
def add_task(self, description, deadline_str=None):
deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
task = Task(description, deadline)
self.tasks.append(task)
self.save_tasks()
print("タスクを追加しました")
def edit_task(self, task_index, description=None, deadline_str=None):
if 1 <= task_index <= len(self.tasks):
task = self.tasks[task_index - 1]
if description:
task.description = description
if deadline_str:
task.deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
self.save_tasks()
print("タスクを編集しました")
else:
print("無効なタスク番号です")
def display_tasks(self):
if not self.tasks:
print("タスクはありません")
else:
print("タスク一覧:")
for i, task in enumerate(self.tasks, 1):
status = "完了" if task.completed else "未完了"
deadline = task.deadline.strftime("%Y-%m-%d %H:%M") if task.deadline else "なし"
print(f"{i}. [{status}] {task.description} (締切: {deadline})")
def mark_task_completed(self, task_index):
if 1 <= task_index <= len(self.tasks):
task = self.tasks[task_index - 1]
task.completed = True
self.save_tasks()
print(f"タスク '{task.description}' を完了にしました")
else:
print("無効なタスク番号です")
def delete_task(self, task_index):
if 1 <= task_index <= len(self.tasks):
deleted_task = self.tasks.pop(task_index - 1)
self.save_tasks()
print(f"タスク '{deleted_task.description}' を削除しました")
else:
print("無効なタスク番号です")
def main():
filename = "tasks.json"
task_list = TaskList(filename)
while True:
print("\n操作を選択してください:")
print("1. タスクを追加")
print("2. タスクを編集")
print("3. タスク一覧を表示")
print("4. タスクを完了にする")
print("5. タスクを削除する")
print("6. 終了")
choice = input("選択 (1/2/3/4/5/6): ")
if choice == '6':
break
elif choice == '1':
description = input("新しいタスクの説明を入力してください: ")
deadline_str = input("締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力可): ")
task_list.add_task(description, deadline_str)
elif choice == '2':
task_list.display_tasks()
task_index = int(input("編集するタスクの番号を入力してください: "))
description = input("新しい説明を入力してください (未入力で変更なし): ")
deadline_str = input("新しい締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力で変更なし): ")
task_list.edit_task(task_index, description, deadline_str)
elif choice == '3':
task_list.display_tasks()
elif choice == '4':
task_list.display_tasks()
task_index = int(input("完了にするタスクの番号を入力してください: "))
task_list.mark_task_completed(task_index)
elif choice == '5':
task_list.display_tasks()
task_index = int(input("削除するタスクの番号を入力してください: "))
task_list.delete_task(task_index)
else:
print("無効な選択です")
if __name__ == "__main__":
main()
python 検索エンジン
# データ
documents = [
"Python is a popular programming language.",
"It is known for its simplicity and readability.",
"Python has a large community of developers.",
"Python is widely used in web development."
]
# データの前処理
def preprocess(text):
return text.lower()
# インデックスの作成
def create_index(documents):
index = {}
for doc_id, doc in enumerate(documents):
doc = preprocess(doc)
words = doc.split()
for word in words:
if word not in index:
index[word] = []
index[word].append(doc_id)
return index
# クエリ処理
def search(query, index):
query = preprocess(query)
words = query.split()
result = set(range(len(documents)))
for word in words:
if word in index:
result &= set(index[word])
return [documents[i] for i in result]
# メイン
if __name__ == "__main__":
index = create_index(documents)
while True:
query = input("検索クエリを入力してください (終了するには 'exit' を入力): ")
if query == 'exit':
break
results = search(query, index)
if results:
for i, result in enumerate(results, start=1):
print(f"{i}. {result}")
else:
print("一致する文書はありません。")
python todoリスト
import os
# ファイル名
todo_filename = 'todo.txt'
# TODOリストを表示する関数
def show_todo_list():
if os.path.exists(todo_filename):
with open(todo_filename, 'r') as file:
todo_list = file.readlines()
if todo_list:
print("TODOリスト:")
for i, item in enumerate(todo_list, start=1):
print(f"{i}. {item.strip()}")
else:
print("TODOリストは空です。")
else:
print("TODOリストはまだ作成されていません。")
# TODOアイテムを追加する関数
def add_todo_item(item):
with open(todo_filename, 'a') as file:
file.write(item + '\n')
print(f"'{item}' をTODOリストに追加しました。")
# TODOアイテムを削除する関数
def remove_todo_item(item_number):
if os.path.exists(todo_filename):
with open(todo_filename, 'r') as file:
todo_list = file.readlines()
if 1 <= item_number <= len(todo_list):
removed_item = todo_list.pop(item_number - 1).strip()
with open(todo_filename, 'w') as file:
file.writelines(todo_list)
print(f"'{removed_item}' をTODOリストから削除しました。")
else:
print("指定された番号のTODOアイテムは存在しません。")
else:
print("TODOリストはまだ作成されていません。")
# メインメニューを表示する関数
def main_menu():
while True:
print("\nメニュー:")
print("1. TODOリストを表示")
print("2. TODOアイテムを追加")
print("3. TODOアイテムを削除")
print("4. 終了")
choice = input("選択してください: ")
if choice == '1':
show_todo_list()
elif choice == '2':
item = input("追加するTODOアイテムを入力してください: ")
add_todo_item(item)
elif choice == '3':
show_todo_list()
item_number = int(input("削除するTODOアイテムの番号を入力してください: "))
remove_todo_item(item_number)
elif choice == '4':
print("アプリケーションを終了します。")
break
else:
print("無効な選択です。再度選択してください。")
if __name__ == "__main__":
main_menu()
python @staticmethod
class HtmlHelper:
@staticmethod
def to_h1(str):
return f"<h1>{str}</h1>"
@staticmethod
def to_p(str):
return f"<p>{str}</p>"
print(HtmlHelper.to_h1("Hello"))
print(HtmlHelper.to_p("Wow"))