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

counting frequency of letters in text using matlab

假设我们有以下文本

s='i love georgia and its nature';

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

 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);

returns未排序的字符串s的字母元胞数组space,这里是它对应的代码

 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

当我 运行 这段代码时,我得到了下图

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

您可以使用 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);

或者不这样做,您可以只使用 uniquestable 输入来确保它们按出现顺序排列。

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'))

将此作为更简单的方法怎么样?

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)

输出:

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

编辑:

您可以使用这些线代替上面的线进行绘图,这样只有具有 non-zero 频率的字母才会被绘制

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

输出: