我有一个大约9000个小写单词的文本文件。我想找到每个单词中最后一个字母的概率(字母的频率/单词的数量)。
这是我第一次去:
function [ prma ] = problast()
counts = zeros(1,26);
%refer to cell index here to get alphabetic number of char
s = regexp('abcdefghijklmnopqrstuvwxyz','.','match');
f = fopen('nouns.txt');
ns = textscan(f,'%s');
fclose(f);
%8960 is the length of the file
for i =1:8960
c = substr(ns(i),-1,1);
num = find(s == c);
counts(num) = num;
end
prma = counts / 8960;
disp(prma);
这给了我这个错误:
Undefined function 'substr' for input arguments of type 'cell'.
有什么想法吗?
答案 0 :(得分:3)
首先,您的问题不需要regexp
。一个非常简单有效的解决方案是:
clear;
close;
clc;
counts = zeros(1,26);
f = fopen('nouns.txt');
ns = textscan(f,'%s');
fclose(f);
for i =1:numel(ns{1})
c = ns{1}{i}(end);
counts('c'-96) = counts('c'-96)+1;
end
prma = counts / numel(ns{1});
disp(prma);
例如,如果"noun.txt"
包含
paris
london
输出将是:
Columns 1 through 8
0 0 0 0 0 0 0 0
Columns 9 through 16
0 0 0 0 0 0.5000 0 0
Columns 17 through 24
0 0 0.5000 0 0 0 0 0
Columns 25 through 26
0 0
答案 1 :(得分:2)
textscan
文档说明结果为cell array。如果你不熟悉单元格数组,我强烈建议你阅读我给出的链接,但是它的长短之处在于你的代码应该是这样的:
c = substr(ns{i},-1,1);
请注意从(
)
到{
}
的更改 - 这是访问单元数组元素的方式。
答案 2 :(得分:2)
怎么样:
f = fopen('nouns.txt');
ns = textscan(f, '%s');
fclose(f);
num = cellfun(@(x)(x(end) - 'a' + 1), ns{:}); %// Convert to 1-26
counts = hist(num, 1:26); %// Count occurrences
prob = counts / numel(ns{:}) %// Compute probabilities
答案 3 :(得分:1)
不确定导致问题的原因,但假设ns{i}
包含您的字符串,这应该可以解决问题:
str = ns{i};
c = str(end);
如果这不起作用,那么根据str
ns
不应该太难。
答案 4 :(得分:0)
感谢大家的建议,我自己解决了这个问题,但我回去试了最后一个答案,结果很好。这就是我想出的:
%Keep track of counts
counts = zeros(1,26);
%Refer to this array to get alphabetic numeric value of character
s = regexp('abcdefghijklmnopqrstuvwxyz','.','match');
f = fopen('nouns.txt');
ns = textscan(f,'%s');
fclose(f);
%8960 = length of nouns.txt
for i =1:8960
%string from vs
str = ns{1}{i};
%last character in that string
c = str(length(str));
%index in s
temp = strfind(s,c);
index = find(not(cellfun('isempty',temp)));
counts(index) = counts(index)+1;
end
%Get probabilities
prma = counts / 8960;
disp(prma);
我投票给所有人帮助我进行头脑风暴。