0

我在 Matlab 中有一个单元格,里面有 5 个字符串,每个字符串都是一个句子,我想使用 Matlab 命令提取每个句子中特殊字符的数量和元音的数量。我该怎么做?

这是我的代码:

sentences={['Dogs are cool!'];['They love to have their bellies scratched!'];['They     love to run around and play in the grass.'];['Each normal year is equal to seven dog years.'];['Its sad when dogs die.']}
sentences1=length(sentences{1})
sentences2=length(sentences{2})
sentences3=length(sentences{3})
sentences4=length(sentences{4})
sentences5=length(sentences{5})
fprintf('There are %d, %d, %d, %d characters in each sentence respectively. ',     sentences1,sentences2,sentences3,sentences4,sentences5)
4

3 回答 3

2

If you define a special character as not a word character ([a-z_A-Z0-9]) and not whitespace:

cellfun(@(x) numel(regexp(x,'[^\w\s]')),sentences)

In your case, that is just one per sentence. If you just want to count characters that are not word characters, which includes whitespace:

>> cellfun(@(x) numel(regexp(x,'[^\w]')),sentences)
ans =
     3
     7
    14
     9
     5

The vowels case is just:

 cellfun(@(x) numel(regexpi(x,'[aeiou]')),sentences)

Notice this now uses regexpi instead of regexp to ignore, case but you can also expand the pattern to '[AEIOUaeiou]' and use the normal regexp. Depending on your mood, you may also choose to use [aeiouy].

于 2013-11-07T21:39:57.493 回答
1

对于元音:

vowels = 'aeiouAEIOU';
cellfun(@(s) sum(ismember(s,vowels)), sentences)

对于特殊字符,执行相同操作:

specialChar = '!?()-,;.'; % define your special characters
cellfun(@(s) sum(ismember(s,specialChar)), sentences)
于 2013-11-07T21:35:24.780 回答
0

好吧,您可以尝试类似的东西

vowels=['a'; 'e'; 'i' ;'o'; 'u'];
 Vowels_N=0;
 for ii=1:length(sentences)
     for jj=1:length(vowels)
         indx=find(vowels(jj),sentences{ii})
         Vowels_N=Vowels_N+length(indx);
     end
 end 

可能不是最有效的方法,可能是错误的没有测试它只是在这里写了你可以为特殊字符做类似的事情

于 2013-11-07T21:59:24.100 回答