#はじめに
先日参加した人工知能学会(JSAI2020)のトレンドを調べようと思い、プログラムの講演タイトルからWord Cloudを作成しました。
#Word Cloudとは
文章中の単語の出現頻度を調べ、頻度に応じて文字の大きさを変えて図示するものです。ツイートからWord Cloudを作成して、多く呟いている単語を可視化したものなどを見たことがある方もいるのではないでしょうか。
#テキストの用意
こちらからJSAI2020の大会論文集をダウンロードし、index.htmlというファイルを開いてセッション一覧をメモ帳にコピペしました。
プログラムがPDFで公開されている場合は次のようにしてテキストを抽出するといいと思います。
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
input_path = './Program.pdf'
output_path = 'Program.txt'
manager = PDFResourceManager()
with open(output_path, "wb") as output:
with open(input_path, 'rb') as input:
with TextConverter(manager, output, codec='utf-8', laparams=LAParams()) as conv:
interpreter = PDFPageInterpreter(manager, conv)
for page in PDFPage.get_pages(input):
interpreter.process_page(page)
#必要ない情報を削除
日付や発表者など、講演タイトル以外の情報をテキストから削除します。発表者は()で囲まれていたので()の中の文字を削除しました。()の中の文字や時刻・日付の指定は正規表現を使っています。
import re
with open('Program.txt', mode='rt', encoding='utf-8') as fo:
Program = fo.read()
#[]を()に変換
Program = Program.replace("[", "(")
Program = ProgramP.replace("]", ")")
#()で囲まれている文字を削除(この時[]だと削除できないため上記のコードが必要)
Program = re.sub(r'\([^)]*\)', '', Program)
#時刻・日付を削除
Program = re.sub(r'((0?|1)[0-9]|2[0-3])[:][0-5][0-9]?', '', Program)
Program = re.sub(r'2020年([0-1]?[0-9])月([0-3]?[0-9])日?', '', Program)
Program = re.sub('時間・会場', '', Program)
Program = re.sub('セッション', '', Program)
Program = re.sub('発表一覧', '', Program)
Program = re.sub('会場', '', Program)
with open('Program_new.txt', 'w') as f:
print(Program, file=f)
#Word Cloudの作成
from matplotlib import pyplot as plt
from wordcloud import WordCloud
with open('Program_new.txt', mode='rt', encoding='utf-8') as fo:
cloud_text = fo.read()
#font_pathは自分の端末にある日本語フォントを指定
word_cloud = WordCloud(width=640, height=480, font_path="/System/Library/AssetsV2/com_apple_MobileAsset_Font6/c7c8e5cb889b80fff0175bf138a7b66c6f027f21.asset/AssetData/ToppanBunkyuMidashiGothicStdN-ExtraBold.otf").generate(cloud_text)
word_cloud.to_file('wordcloud4.png')
plt.imshow(word_cloud)
plt.axis('off')
plt.show()