2015-06-21 31 views
2

我需要与上字母输入句子,然后拆分句子的单词和字符的每一个字计数“一”拆分句子的单词和计数的字符数“A”中的每个字

我VE使这个

clear 
sentences=input('Write your sentences: ','s'); 
low=lower(sentences); 
disp('Sentences splitted to words: '); 
words=regexp(low,' ','split'); 
for i=1:length(words) 
    disp(words(i)) 
end 

现在我不知道如何计算每个分割后的单词“一”字,因为这些词被转换成细胞。 有人可以帮助我吗?

+0

从这里开始:

count = cellfun(@(w) sum(w=='a'), words); 

您可以同样使用一个循环文档:[字符和字符串](http://www.mathworks.com/help/matlab/characters-and-strings.html) – horchler

+0

没有必要在标题中人为插入标签;理想情况下,标题应该是连贯的句子 – 2015-06-24 20:11:04

回答

0

处理每个单元格,使用cellfunanonymous function计数'a'发生在每个单词的次数:在

N = numel(words); 
count = NaN(1,N); %// preallocate for speed 
for n = 1:N 
    w = words{n}; 
    count(n) = sum(w=='a'); 
end 
+0

'w =='a''对于字符串来说通常是不好的做法(除非一个字符串执行一组输入验证)。 'strfind'可能是更好的选择:'count = cellfun('length',strfind(words,'a'))''。 – horchler

+0

使用'=='测试两个字符串是否是不好的做法(它们可能有不同的长度),但我认为将字符串与_character_进行比较并不是一个坏习惯。或者我错过了什么? –

相关问题