%% Prepare Text Data for Word Clouds
% If you have Text Analytics Toolbox™ installed, then you can create word clouds directly from string arrays. For more information, see wordcloud (Text Analytics Toolbox). If you do not have Text Analytics Toolbox, then you must preprocess the text data manually.
% This example shows how to create a word cloud from plain text by reading it into a string array, preprocessing it, and passing it to the wordcloud function.
% Read the text from Shakespeare's Sonnets with the fileread function and convert it to string.

sonnets = string(fileread('sonnets.txt'));
extractBefore(sonnets,"II")

% Split sonnets into a string array whose elements contain individual words. To do this, remove the punctuation characters and join all the string elements into a 1-by-1 string and then split on the space characters. Then, remove words with fewer than five characters and convert the words to lowercase.

punctuationCharacters = ["." "?" "!" "," ";" ":"];
sonnets = replace(sonnets,punctuationCharacters," ");
words = split(join(sonnets));
words(strlength(words)<5) = [];
words = lower(words);
words(1:10)

% Convert sonnets to a categorical array and then plot using wordcloud. The function plots the unique elements of C with sizes corresponding to their frequency counts.

C = categorical(words);
figure
wordcloud(C);
title("Sonnets Word Cloud")

% Copyright 2012 The MathWorks, Inc.