Main Content

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 함수를 사용하여 텍스트를 문자열로 변환합니다. 그런 다음, 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")

Figure contains an object of type wordcloud. The chart of type wordcloud has title Sonnets Word Cloud.

참고 항목

|