1
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?

SudachiPyとCounter/pandasで実現するテキストデータの形態素頻度分析と特定品詞フィルタリング

1
Posted at

日本語テキストから「高頻度で出現する重要語」や「特定の感情・状態を表す品詞」を抽出・集計することは、テキストマイニングや感情分析の基礎です。

本記事では、SudachiPyでテキストを最小単位(Mode A)に分解し、Python標準の collections.Counter および pandas を使って特定の品詞(名詞・形容詞・動詞)を効率的にカウント・集計する方法を解説します。


1. 開発環境と事前準備

必要なパッケージを導入します。形態素解析にSudachiPy、データの集計・整理にpandasを使用します。

pip install sudachipy sudachidict_core pandas


2. 形態素抽出&品詞フィルタリング関数

テキストを入力として受け取り、指定した品詞の「正規化形(原形)」のリストを返す汎用関数を作成します。

from collections import Counter
from sudachipy import dictionary, tokenizer

# DictionaryとTokenizerの初期化
tokenizer_obj = dictionary.Dictionary().create()


def extract_pos_words(
    text: str, target_pos: list[str], mode=tokenizer.Tokenizer.SplitMode.A
) -> list[str]:
    """指定された品詞(大分類)に該当する形態素の原形リストを返します。

    :param text: 解析対象テキスト
    :param target_pos: 抽出したい品詞のリスト (例: ["名詞", "形容詞"])
    :param mode: SudachiPyの分割モード (デフォルト: Mode A)
    :return: 抽出された単語(原形)のリスト
    """
    tokens = tokenizer_obj.tokenize(text, mode)
    words = []

    for t in tokens:
        pos_category = t.part_of_speech()[0]

        # 抽出対象の品詞に合致し、かつ1文字以下の不要な記号等を除外
        if pos_category in target_pos:
            norm_form = t.normalized_form()
            # 数字や単一の補助記号などを除外したい場合の簡易フィルタ
            if len(norm_form) > 1 or pos_category == "名詞":
                words.append(norm_form)

    return words


3. collections.Counter による頻度集計

抽出した単語リストから、出現頻度の高いトップNの単語を取得します。

# サンプルテキスト(レスバやSNSの感情的テキストを模したデータ)
sample_text = """
相手の論理は完全に論外であり、勝てる要素が一切ない。
不快な発言に対して許せない感情が爆発し、激しい被害を受けた。
論破を試みるも相手は論外な態度を取り、不満と不快感が募るばかりだ。
"""

# 名詞と形容詞のみを抽出
words = extract_pos_words(sample_text, target_pos=["名詞", "形容詞"])

# Counterで出現頻度をカウント
word_counts = Counter(words)

print("=== 出現頻度 TOP 5 ===")
for word, count in word_counts.most_common(5):
    print(f"{word}: {count}")

実行結果

=== 出現頻度 TOP 5 ===
論外: 2回
不快: 2回
相手: 2回
論理: 1回
勝てる: 1回


4. pandas.DataFrame による高度なデータ集計と可視化

複数テキストや大量のログデータを解析する場合は、pandas のデータフレームへ変換することで品詞ごとのクロス集計やCSV出力が容易になります。

import pandas as pd

# 形態素の詳細情報をDataFrame化する処理
tokens = tokenizer_obj.tokenize(sample_text, tokenizer.Tokenizer.SplitMode.A)

data = []
for t in tokens:
    pos = t.part_of_speech()
    data.append(
        {
            "表層形": t.surface(),
            "原形": t.normalized_form(),
            "品詞": pos[0],
            "品詞細分類": pos[1],
            "読み": t.reading_form(),
        }
    )

df = pd.DataFrame(data)

# 1. 記号などを除外
df_filtered = df[~df["品詞"].isin(["補助記号", "助詞", "助動詞"])]

# 2. 品詞別の出現ランキング
print("=== 品詞別カウント件数 ===")
print(df_filtered["品詞"].value_counts())

print("\n=== 名詞の頻度上位 ===")
print(
    df_filtered[df_filtered["品詞"] == "名詞"]["原形"].value_counts().head(5)
)


5. まとめ

  • SudachiPynormalized_form() と品詞情報(part_of_speech())を組み合わせることで、ノイズ(助詞や活用形の違い)を除去したクリアなテキストマイニングが可能になります。
  • Mode Aで分解することで単語を最小単位まで解剖できるため、感情表現(形容詞)や主題(名詞)の出現比率を正確に計測できます。
  • 大量データの集計には Counterpandas との連携が非常に強力です。
1
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
1
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?