How do I specify that I wish to count the number of vowels in a text document in MatLab?

조회 수: 5 (최근 30일)
I'm working on a code that would scan a text file and output the number of vowels in the document i.e 'This file contains x vowels'
This is what I've done so far:
fid=fopen('doc.txt','r');
vowel_set='AaEeIiOoUu';
vowels=0
while ~feof(fid)
if strfind(vowel_set,c)
vowels=vowels+1
end
break;
end
message=sprintf('This file contains %d vowels.', vowels)'; disp(message);
What am I doing wrong? Thanks a million in advance
  댓글 수: 6
Walter Roberson
Walter Roberson 2012년 9월 4일
In English, "y" is usually a consonant when it starts a syllable, but usually a vowel in other positions in a syllable. For example, "yellow" starts with a consonant, but "try" ends with a vowel. There are also uncommon cases where an initial "y" is a vowel, such as "Ytterbium"
Jan
Jan 2012년 9월 4일
편집: Jan 2012년 9월 4일
It is called "a unit", not "an unit" (if I remember correctly). So sometimes even the "u" can be a little bit unvowelish.

댓글을 달려면 로그인하십시오.

답변 (2개)

Daniel Shub
Daniel Shub 2012년 9월 4일
Assuming you have some text saved in a char array called x
length(regexpi(x, 'a|e|i|o|u'))

Jan
Jan 2012년 9월 4일
편집: Jan 2012년 9월 4일
You do not define a variable called "c". Perhaps you want to add a fgets()? The break stops the loop after the first iteration. strfind replies a vector, which can be empty. Therefore using "if strfind()" does not do, what you need. The any() command would be more helpful - but not sufficient, because you want to know the number.
I suggest fileread or at least reading the complete file at once:
fid = fopen('doc.txt','r');
str = fread(fid, Inf, '*char');
Then ismember will helpful to identify the vowels.
  댓글 수: 2
Ari
Ari 2012년 9월 4일
I'm not familiar with the ismember handle. I only started using MatLab a few weeks ago so I'm quite new to it all.
Jan
Jan 2012년 9월 4일
Type "help ismember" and "doc ismember" in the command line. Then consider, that "ismember" does exactly what its name implies. It takes one set of elements (your string imported from the file) and checks if they are member of a second set of elements (the string of vowels you have defined already). Then you get a 1 for each member and a 0 for each non-member. And the sum of the reply is the number of vowels.
Welcome to Matlab!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by