MATLAB: How to count the no of words in a sentence

watermarking

i have read the text file sentence by sentence by using the following code. now i want to count the total no of words in each sentence.. how can i do that? i know how to read a text file word by word but it gives total no of words in the whole document and i want to calculate no of words for each sentence separately.
fid=fopen('hello.txt');
text = textread('hello.txt','%s','delimiter','.')
fclose(fid);
[r,c]=size(text)

Best Answer

txt = fileread('hello.txt'); %read in file, assuming it is not too big
sentences = strtrim(regexp(txt, '[\.\?\!]+', 'split')); %split into sentences
%I assume that sentences end with ., ?, or !, which don't appear elsewhere in
% the file (i.e., no quoted strings, abbreviations containing '.', etc.).
words = regexp(sentences, '\s+', 'start'); % find spaces (which separate words)
wordsPerSentence = cellfun(@length, words, 'UniformOutput', true); %count words
%we only care about sentences containing at least one word.
wordsPerSentence = wordsPerSentence(wordsPerSentence>=1)+1;
Related Question