0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

スクレイピングしたニュースタイトルを形態素解析してwordCloudを作成する

Last updated at Posted at 2021-11-10

前提

こちらは前回の続きになります。
「RequestsとBeautifulSoupを使用してニュースをスクレイピングし、CSV出力する」
https://qiita.com/yu_ku/items/c9480c1b6c2e804cb104

形態素解析とは...

形態素解析(Morphological Analysis)
自然言語処理分野で主に事前処理として用いられる手法で、対象となる言語の文法や単語の情報をもとに、文章を形態素(単語が意味を持つ最小の単位)に分解する解析方法。

下記をインストールする

pip install mecab-python3
pip install wordcloud
pip install DateTime

main.pyでスクレイピングしたデータを形態素解析後にカウントし、CSVファイルに出力する

import MeCab
from wordcloud import WordCloud
import crawler
import datetime as dt

now = dt.datetime.now()
time = now.strftime('%Y%m%d')
wordFreq_dic = {}
wordcount_output = []

wordcount_path = "wordcount/wordcount_dic_"
wordcloud_path = "wordcloud/wordcloud_"

# 解析テキストの準備
cr_data = cr_hatena[1] +  cr_hacker_news[1]
text = ''.join(cr_data)

# 単語頻出度カウントする
def WordFrequencyCount(word):
    if word in wordFreq_dic:
        wordFreq_dic[word] +=1

    else:
        wordFreq_dic.setdefault(word, 1)
    return wordFreq_dic

# 特定の品詞の単語を抽出(形態素解析)
mecab = MeCab.Tagger()
mecab.parse('')
node = mecab.parseToNode(text)

while node:
    if node.feature.split(",")[0] == "名詞":
        word = node.surface
        WordFrequencyCount(word)
    elif node.feature.split(",")[0] =="動詞":
        word = node.surface
        WordFrequencyCount(word)
    elif node.feature.split(",")[0] == "形容詞":
        word = node.surface
        WordFrequencyCount(word)
    elif node.feature.split(",")[0] == "形容動詞":
        word = node.surface
        WordFrequencyCount(word)
    else:pass
    node = node.next

# 辞書リストを取り出し、降順に並び替える
for item in wordFreq_dic.items():
    wordcount_output.append(item)
wordcount_output = sorted(wordcount_output, key = lambda x:x[1], reverse=True)

# 単語のカウント数をCSV出力する
with open(wordcount_path + str(time) + ".csv", "w", encoding="utf-8") as f:
    writer = csv.writer(f, lineterminator="\n")
    writer.writerow(['Word', 'Count'])
    writer.writerows(wordcount_output)

単語頻出度をまとめたCSVからwordCloudを作成する

# CSVファイルを読み込み加工
text = open(wordcount_path + str(time) + ".csv", encoding="utf8").read()
splitted_data = " ".join([x.split("\t")[0] for x in mecab.parse(text).splitlines()[:-1] if x.split("\t")[1].split(",")[0] not in ["助詞", "助動詞"]])

# WordCloudを作成してpngファイルで保存する
wordcloud = WordCloud(background_color="white", width=1000, height=600, font_path="NotoSansJP-Regular.otf")
wordcloud.generate(splitted_data)
wordcloud.to_file(wordcloud_path + str(time) + ".png")

上記のように実装すると下記のように頻出度が高い順に大きい単語が表示されます。
wordcloud_20211003.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?