使用matlab计算文本中字母的频率

时间:2017-01-30 14:04:20

标签: matlab text charts word-frequency

假设我们有以下文字

s='i love georgia and its nature';

我想要的是计算每个字母的出现频率(当然不包括空格)和草绘一些图表(例如条形图),首先我创建了使用地图容器计数字母的代码

 function character_count(s)
    % s is given string and given program will count  occurence of letters in
    % sentence
    MAP=containers.Map();% initialize   MAP for frequency counting
    n=length(s); % get length of given string
    letters=unique_without_space_sorting(s);
    for ii=1:n
        if ~isletter(s(ii))==1
            continue;
        elseif  isKey(MAP,s(ii) )
            MAP(s(ii)) = MAP(s(ii))  + 1;
        else
          MAP(s(ii)) = 1;

        end
    end
      y=values(MAP);
      y= cell2mat(y);
     bar(y);
    set(gca,'xticklabel',letters)

    end

这里的功能

letters=unique_without_space_sorting(s);

返回字符串s的字母数组而不进行排序和空格,这里是其对应的代码

 function cell_stirng=unique_without_space_sorting(s)
    s=regexprep(s,'[^\w'']','');
     [~, idxs, ~] = unique(s, 'last');
     s= s(sort(idxs));
     n=length(s);
     cell_stirng=cell(n,1);
     for jj=1:n
         cell_string{jj}=s(jj);
     end
     end

当我运行此代码时,我得到了以下图像 enter image description here

如您所见,x轴上没有标签,我该如何解决这个问题?提前谢谢

2 个答案:

答案 0 :(得分:5)

您可以使用unique的第一个输出为您提供唯一值,并将其用作x标签

[values, idxs, ~] = unique(s, 'last');

% Make sure that they aren't sorted
[~, sortind] = sort(idxs);
values = num2cell(values(sortind));

% And later after creating your bar plot
set(gca, 'xtick', 1:numel(values), 'XTickLabels', values);

或者不是这样做,您可以使用stable输入unique来确保它们的外观顺序相反。

S = lower(strrep(s, ' ', ''));
[values, ~, b] = unique(S, 'stable');

hist(b, unique(b))
set(gca, 'xtick', 1:numel(values), 'xticklabels', num2cell(values))

或者如果你想要一个所有字母的直方图

S = lower(strrep(s, ' ', ''));
counts = histcounts(double(S), double('a':'z'));
bar(counts)
set(gca, 'xtick', 1:26, 'xticklabels', num2cell('a':'z'))

答案 1 :(得分:1)

这是一个更简单的方法呢?

str = 'i love georgia and its nature';

num_times = zeros(26,1);
letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', ...
           'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

for k = 1:length(str)

    % Convert letter to its lower case, get ASCII value, 
    % a = 97, b = 98, ..., z = 122
    n = uint16(lower(str(k)));

    % If character between 'a' and 'z'
    if n < 122 && n > 97

        % Convert to be between 1 and 26
        n = n - 96;

        % Index count array with n        
        num_times(n) = num_times(n) + 1;

    end

end

clf
stem(num_times);
set(gca, 'XTick', 1:26);
set(gca,'XTickLabel', letters)

输出:

Plot of letter frequency

如果您不想更改其他代码,请参阅我的最后两行标记x轴。

编辑:

您可以使用这些线代替上面的绘图,以便只绘制具有非零频率的字母

clf 
stem(num_times(num_times ~= 0));    
set(gca, 'XTick', 1:sum(num_times ~= 0));
set(gca,'XTickLabel', letters(num_times ~= 0))

输出:

unique letter frequencies