LoginSignup
4
3

More than 1 year has passed since last update.

[Python]Google Chrome検索履歴からWordCloudを生成してStreamlitで可視化する方法 メモ

Posted at
  • Google Chromeの検索履歴データからStreamlitを利用し、頻出単語の一覧表とWordCloudを描画する方法についてメモする。

事前準備

ライブラリインストール

  pip install pandas
  pip install streamlit
  pip install janome
  pip install matplotlib
  pip install wordcloud
  • pandas:データ整形に使用
  • streamlit:データ可視化に使用
  • janome:形態素解析に使用
  • matplotlib:wordcloud描画に使用
  • wordcloud:WordCloud生成に使用

Google Chromeの検索履歴データHistoryを取得する。

  • Windows例
  C:\Users\XXXXXXXX\AppData\Local\Google\Chrome\User Data\Default\History

WordCloud用日本語フォント準備

  • Windowsの場合:以下のフォルダにあるフォントから使用するものを選択しておく。

    C:/Windows/Fonts/...
    

コード

  • wc.py
    • 同一階層にHistoryを配置する。
import streamlit as st
from janome.tokenizer import Tokenizer
import collections
import pandas as pd
import sqlite3
from contextlib import closing
import matplotlib.pyplot as plt
from wordcloud import WordCloud

history = './History'

# ブラウザ履歴データを検索
def search_history():
    browser_history_text = ''

    with closing(sqlite3.connect(history)) as conn:
        c = conn.cursor()
        statements = "select title LONGVARCHAR from 'urls'"
        results= c.execute(statements)
        for result in results:
            browser_history_text += result[0]
    return browser_history_text 


# ブラウザ履歴データを形態素解析
def analyze_history(history: str):
    t = Tokenizer()

    # 頻出単語を取得
    freq_of_words = collections.Counter(token.base_form for token in t.tokenize(history)
                            if token.part_of_speech.startswith('名詞,固有名詞'))
    return freq_of_words 

# WordCloud生成
def generate_wordcloud(analyze_result: str):
    dic_result = dict(analyze_result)
    # フォントファイル名指定
    wordcloud = WordCloud(background_color='white',
                          font_path='C:/Windows/Fonts/...',
                          width=800, height=600).fit_words(dic_result)
    return wordcloud


if __name__ == "__main__":
    browser_history_text = search_history()
    freq_of_words = analyze_history(browser_history_text)
    wordcloud = generate_wordcloud(freq_of_words)
    st.title('ブラウザ検索履歴 分析')

    # Wordcloud描画時の警告を非表示にするため
    st.set_option('deprecation.showPyplotGlobalUse', False)

    # WordCloud 表示
    plt.axis("off")
    plt.tight_layout()
    plt.imshow(wordcloud, interpolation='bilinear')
    st.pyplot()

    # 頻出検索単語表 表示
    df = pd.DataFrame(freq_of_words.most_common()[:10], columns=['単語', '回数'])
    st.dataframe(df)

動作確認

  • 起動
streamlit run wc.py

You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://10.4.113.198:8501

wc_result.png

参考情報

4
3
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
4
3