c 字符串数组_MATLAB作图实例:22:由字符串数组创建词云

0ef40b6d11d32d686a22bf905f86bf15.png

本示例说明如何通过将纯文本读取到字符串数组中,对其进行预处理并将其传递给wordcloud函数来从纯文本创建词云。如果安装了Text Analytics Toolbox,则可以直接从字符串数组创建词云。有关更多信息,请参见wordcloud(文本分析工具箱)。

使用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 = 5x1 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 = 5x1 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为一个字符串数组,其元素包含单个单词。为此,将所有字符串元素连接成1×1字符串,然后在空格字符处拆分。

 sonnets = join(sonnets);
 sonnets = split(sonnets);
 sonnets(7:12)
 ans = 6x1 string
     "From"
     "fairest"
     "creatures"
     "we"
     "desire"
     "increase"

删除少于五个字符的单词。

 sonnets(strlength(sonnets)<5) = [];

转换sonnets为分类数组,然后使用绘制wordcloud。该函数绘制C中的每一个元素,元素大小与它们的频率计数相对应。

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

4326dec5a248c2542cfc4f7680de985b.png

注:本文根据MATLAB官网内容修改而成。

我推荐给你以下的视频教程,特点是没有PPT,不掺水,直接编程环境下的实操课程: 用100分钟了解MATLAB编程

知乎 - 安全中心​www.1data.pro

《MATLAB编程360》视频课程:

MATLAB编程360 - 网易云课堂study.163.com​study.163.com
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值