Pythonリストと辞書の実践的応用事例

バースデーパラドックスの検証

23人以上のグループで誕生日が重複する確率が50%を超える現象を検証する。異なるサンプルサイズでの確率を計算する。

import random

def 誕生日重複チェック():
    birthdays = [random.randint(1, 365) for _ in range(23)]
    return len(birthdays) != len(set(birthdays))

def 確率計算(試行回数):
    重複数 = 0
    for _ in range(試行回数):
        if 誕生日重複チェック():
            重複数 += 1
    return 重複数 / 試行回数

サンプルサイズ = [100, 1000, 10000, 100000]
for size in サンプルサイズ:
    prob = 確率計算(size)
    print(f"サンプル数:{size} 確率:{prob:.4f}")

テキスト分析とワードクラウド生成

小説テキストから上位10の高頻度単語を抽出し、可視化する。

import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def テキスト分析(ファイルパス):
    with open(ファイルパス, 'r', encoding='utf-8') as f:
        text = f.read()
    
    単語リスト = jieba.lcut(text)
    除外語 = {'の', '、', '。', 'は', 'が', 'で', 'に'}
    フィルタ済み = [w for w in 単語リスト if w not in 除外語 and len(w) > 1]
    
    単語頻度 = Counter(フィルタ済み)
    トップ10 = 単語頻度.most_common(10)
    
    wordcloud = WordCloud(
        font_path='simhei.ttf', 
        background_color='white'
    ).generate_from_frequencies(単語頻度)
    
    plt.imshow(wordcloud)
    plt.axis('off')
    plt.show()

テキスト分析('yi.txt')

武侠小説の文体分析

複数作品の高頻出単語を比較し、作家のスタイル特性を抽出する。

import jieba
from collections import Counter
import re

def 単語頻度分析(ファイル, 表示数=10):
    with open(ファイル, 'r', encoding='utf-8') as f:
        text = f.read()
    
    単語 = jieba.lcut(text)
    ストップワード = {'こと', 'よう', 'それ', 'これ', 'さん', 'ない', 'ある', 'いる'}
    フィルタ済み = [w for w in 単語 if w not in ストップワード and len(w) > 1]
    
    return Counter(フィルタ済み).most_common(表示数)

小説ファイル = ['天龍八部.txt', '神鵰俠侶.txt']
for ファイル in 小説ファイル:
    print(f"{ファイル} 高頻出単語:")
    for 単語, _ in 単語頻度分析(ファイル):
        print(単語)
    print("------")

金庸作品の特徴: 中国伝統文化と歴史的背景を基盤に、善悪の対立や複雑な人間関係を描写。武術描写より人間ドラマに重点を置き、多様な愛情表現が物語を深化させる。

タグ: Python バースデーパラドックス テキスト分析 ワードクラウド 金庸

7月25日 23:34 投稿