LoginSignup
1
1

More than 1 year has passed since last update.

【Python】CSVファイルの内容をspaCyとGiNZAで解析してワードクラウド化

Posted at

はじめに

グーグル検索結果のタイトルとリンクをCSVファイルに保存するようにした
【Python】グーグル検索結果のタイトルとリンクをCSVファイルに保存(ページ移動有)

CSVファイルから文章を抜き出して、ワードクラウド化と単語の出現頻度をグラフ化していく~

仕様

・csvファイルの処理対象のデータは"title"というヘッダーの列
・csvファイルの文字コードは"UTF-8","cp932"のいずれか
・処理対象データの単語の出現頻度はcsvファイル(①)に保存
・処理対象データの単語の出現頻度Top10はグラフ化してPNGファイル(②)で保存
・形態素解析は自然言語ライブラリspaCyと日本語NLPライブラリGiNZAを使用
・解析結果をもとにワードクラウド化してPNGファイル(③)で保存
・①~③のファイル名は「"unko"+α」※コード上の"filename"で指定

コード

import spacy
nlp = spacy.load('ja_ginza')
import pandas as pd
import matplotlib.pyplot as plt
import japanize_matplotlib # グラフの日本語が文字化けしないために必要
import collections
from wordcloud import WordCloud

### GiNZA統計モデルで分析した結果をリストにして返す関数
def analyze_by_ginza(words):
    # GiNZA統計モデルに文章を渡して分析
    doc = nlp(words)
    # 分析結果をリストに格納する
    word_list = []
    chunk_list = [chunk.text for chunk in doc.noun_chunks]
    token_list = [token.lemma_ for token in doc if token.pos_ == "VERB"]
    for i in chunk_list:
        word_list.append(i)
    for j in token_list:
        word_list.append(j)
    return word_list


### 処理対象CSVファイル読み込み処理
# ファイルパスの指定
csv_read_path = "result.csv"

# ファイル読み込み。UTF-8,cp932でだめならファイルが存在ないとしてエラー
try:
    df_r = pd.read_csv(csv_read_path, encoding="utf_8_sig")
except UnicodeDecodeError:
    df_r = pd.read_csv(csv_read_path, encoding="cp932")
except FileNotFoundError:
    print('File not found.')

# 読み込んだCSVファイルの処理対象のタグ
target_categories = ["title"]

# 処理結果を保存する際のファイル名
filename = "unko"


### 形態素分析とワードクラウド化
for target in target_categories:
    total_word = [] # 文字を入れる箱を用意
    for data in df_r[target]:
        try:
            word_list = analyze_by_ginza(data)
        except Exception as e:
            # リストではない場合は単語なので、そのままリスト化
            word_list = [data]
            # 念のためエラー内容をプリント
            print(e)
        for w in word_list:
            total_word.append(w)

    print("単語数: ", len(total_word))

    # 最頻単語を順位づけ
    count = collections.Counter(total_word)

    # CSVに書き込む
    count_data = count.most_common()
    df_w = pd.DataFrame(count_data) 
    df_w.to_csv(filename+".csv", encoding="utf_8_sig")

    # グラフ化して保存する
    fig = plt.figure()
    plt.title(target)
    plt.grid(True)
    x_list = [] # グラフのx軸となるデータの箱
    y_list = [] # グラフのy軸となるデータの箱
    rank_num = 0
    for key, value in count.most_common():
        x_list.append(key)
        y_list.append(value)
        if rank_num >= 10: # Top10までグラフ化
            break
        rank_num += 1
    try:
        # 棒グラフを作成
        plt.bar(x_list, y_list)
        # グラフの保存
        fig.savefig(filename+"_graph.png")
    except Exception as e:
        print(target, " は以下の理由でデータを描画できません↓↓↓")
        print(e)

    # WordCloud を作成して保存する
    fpath = "C:/Windows/Fonts/meiryo.ttc" # メイリオ
    wordcloud = WordCloud(background_color="white",
                          width=800,
                          height=600,
                          font_path=fpath)
    wordcloud.generate(" ".join(total_word))
    wordcloud.to_file(filename+'.png')
1
1
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
1