1. sys
sys
モジュールは、Pythonインタプリタと対話するための機能を提供します。
例えば、コマンドライン引数の取得やプログラムの終了などに使います。
import sys
# コマンドライン引数の取得
args = sys.argv
print(f"コマンドライン引数: {args}")
# コマンドライン引数: ['script.py']
# プログラムの終了
if len(args) < 2:
print("引数が足りません")
sys.exit(1)
# 引数が足りません
2. math
math
モジュールは、数学関数を提供します。
例えば、平方根や対数、三角関数などを使うことができます。
import math
# 平方根の計算
print(f"16の平方根: {math.sqrt(16)}")
# 16の平方根: 4.0
# 対数の計算
print(f"1000の自然対数: {math.log(1000)}")
# 1000の自然対数: 6.907755278982137
# 三角関数の計算
print(f"30度のサイン: {math.sin(math.radians(30))}")
# 30度のサイン: 0.49999999999999994
3. datetime
datetime
モジュールは、日付や時刻を扱うためのクラスを提供します。
例えば、現在の日時の取得や日時の差分の計算に使います。
from datetime import datetime, timedelta
# 現在の日時を取得
now = datetime.now()
print(f"現在の日時: {now}")
# 現在の日時: 2024-06-10 14:15:16.123456
# 10日後の日時を計算
future_date = now + timedelta(days=10)
print(f"10日後の日時: {future_date}")
# 10日後の日時: 2024-06-20 14:15:16.123456
# 日時の差分を計算
diff = future_date - now
print(f"差分: {diff.days}日")
# 差分: 10日
4. time
time
モジュールは、時間に関する関数を提供します。
例えば、プログラムの実行を遅延させたり、経過時間を測定したりします。
import time
# 5秒間待つ
print("5秒待ちます...")
time.sleep(5)
print("5秒経過しました")
# 5秒待ちます...
# 5秒経過しました
# 経過時間の測定
start_time = time.time()
time.sleep(2)
end_time = time.time()
print(f"処理時間: {end_time - start_time}秒")
# 処理時間: 2.002秒
5. tkinter
tkinter
モジュールは、PythonでGUIアプリケーションを作成するための標準ライブラリです。
import tkinter as tk
# ウィンドウの作成
root = tk.Tk()
root.title("Hello Tkinter")
# ラベルの作成
label = tk.Label(root, text="Hello, World!")
label.pack()
# ボタンの作成
def on_button_click():
label.config(text="Button Clicked!")
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()
# ウィンドウの表示
root.mainloop()
6. json
json
モジュールは、JSONデータのエンコードとデコードを行います。
import json
# 辞書をJSON文字列に変換
data = {"name": "Alice", "age": 30, "city": "Tokyo"}
json_str = json.dumps(data)
print(f"JSON文字列: {json_str}")
# JSON文字列: {"name": "Alice", "age": 30, "city": "Tokyo"}
# JSON文字列を辞書に変換
data_dict = json.loads(json_str)
print(f"辞書: {data_dict}")
# 辞書: {'name': 'Alice', 'age': 30, 'city': 'Tokyo'}
7. random
random
モジュールは、ランダムな数を生成します。
例えば、ランダムな整数や選択を行うことができます。
import random
# ランダムな整数を生成
print(f"1から10のランダムな整数: {random.randint(1, 10)}")
# 1から10のランダムな整数: 7
# ランダムな要素を選択
choices = ['apple', 'banana', 'cherry']
print(f"ランダムな選択: {random.choice(choices)}")
# ランダムな選択: banana
# リストをランダムにシャッフル
random.shuffle(choices)
print(f"シャッフル後: {choices}")
# シャッフル後: ['cherry', 'banana', 'apple']
8. pip
pip
は、Pythonパッケージの管理ツールです。
例えば、パッケージのインストールやアンインストールを行います。
# パッケージのインストール
pip install requests
# パッケージのアンインストール
pip uninstall requests
# インストール済みパッケージの一覧表示
pip list
9. Pillow
Pillow
は、画像処理を行うためのライブラリです。
例えば、画像の読み込み、加工、保存を行います。
from PIL import Image
# 画像の読み込み
image = Image.open('example.jpg')
# 画像のサイズ変更
resized_image = image.resize((200, 200))
# 画像の保存
resized_image.save('resized_example.jpg')
print("画像を保存しました")
10. os
os
モジュールは、オペレーティングシステムとの対話を行います。
例えば、ファイルやディレクトリの操作を行います。
import os
# カレントディレクトリの取得
current_dir = os.getcwd()
print(f"カレントディレクトリ: {current_dir}")
# カレントディレクトリ: /path/to/current/directory
# ファイルやディレクトリの一覧表示
files = os.listdir(current_dir)
print(f"ファイルとディレクトリ: {files}")
# ファイルとディレクトリ: ['file1.txt', 'file2.txt', 'example.jpg']
# 新しいディレクトリの作成
os.mkdir('new_directory')
print("新しいディレクトリを作成しました")
11. re
re
モジュールは、正規表現を使った文字列操作を行います。
import re
# 正規表現パターンのコンパイル
pattern = re.compile(r'\d+')
# パターンにマッチする部分を検索
text = "The price is 100 dollars"
matches = pattern.findall(text)
print(f"マッチした部分: {matches}")
# マッチした部分: ['100']
# パターンにマッチする部分を置換
replaced_text = pattern.sub('###', text)
print(f"置換後のテキスト: {replaced_text}")
# 置換後のテキスト: The price is ### dollars
12. calendar
calendar
モジュールは、カレンダーに関する機能を提供します。
import calendar
# 特定の月のカレンダーを表示
year = 2024
month = 6
print(calendar.month(year, month))
# June 2024
# Mo Tu We Th Fr Sa Su
# 1 2
# 3 4 5 6 7 8 9
#
10 11 12 13 14 15 16
# 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30
# うるう年の判定
is_leap = calendar.isleap(year)
print(f"{year}はうるう年ですか? {is_leap}")
# 2024はうるう年ですか? True
# 特定の年のうるう年の数を取得
leap_days = calendar.leapdays(2000, 2025)
print(f"2000年から2025年までのうるう年の数: {leap_days}")
# 2000年から2025年までのうるう年の数: 7
以上