string 配列からのワードクラウドの作成
この例では、プレーン テキストから string 配列に読み取り、前処理して、それを関数 wordcloud
に渡して、ワード クラウドを作成する方法を示します。Text Analytics Toolbox™ がインストールされている場合は、string 配列から直接ワード クラウドを作成できます。詳細については、wordcloud
(Text Analytics Toolbox)(Text Analytics Toolbox) を参照してください。
関数 fileread
を使用して、シェークスピアのソネットからテキストを読み取ります。
sonnets = fileread('sonnets.txt');
sonnets(1:135)
ans = 'THE SONNETS by William Shakespeare I From fairest creatures we desire increase, That thereby beauty's rose might never die,'
関数 string
を使用して、テキストを string に変換します。次に、関数 splitlines
を使用して、改行文字の位置で分割します。
sonnets = string(sonnets); sonnets = splitlines(sonnets); sonnets(10:14)
ans = 5×1 string
" From fairest creatures we desire increase,"
" That thereby beauty's rose might never die,"
" But as the riper should by time decease,"
" His tender heir might bear his memory:"
" But thou, contracted to thine own bright eyes,"
一部の句読点をスペースに置き換えます。
p = ["." "?" "!" "," ";" ":"]; sonnets = replace(sonnets,p," "); sonnets(10:14)
ans = 5×1 string
" From fairest creatures we desire increase "
" That thereby beauty's rose might never die "
" But as the riper should by time decease "
" His tender heir might bear his memory "
" But thou contracted to thine own bright eyes "
sonnets
を、個々の単語を要素として含む string 配列に分割します。これを行うには、すべての string 要素を 1 行 1 列の string に結合して、空白文字の位置で分割します。
sonnets = join(sonnets); sonnets = split(sonnets); sonnets(7:12)
ans = 6×1 string
"From"
"fairest"
"creatures"
"we"
"desire"
"increase"
5 文字未満の語を削除します。
sonnets(strlength(sonnets)<5) = [];
sonnets
を categorical 配列に変換して、wordcloud
を使用してプロットします。この関数は C
の一意の要素を、その頻度数に対応するサイズでプロットします。
C = categorical(sonnets);
figure
wordcloud(C);
title("Sonnets Word Cloud")