How to count the number of each character from a text file (and the frequency of it)?

57 ビュー (過去 30 日間)
Create a function that takes a text file as input and returns a vector of size 26 with the frequency in percent of each character a, b, . . . z (not sensitive to case.) The frequency must be computed as the number of occurences divided by the total number of characters from a to z that occur, multiplied by one hundred. All other letters such as ø and ä as well as all symbols must be ignored.

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 3 月 28 日
s=importdata('file.txt')
str=upper(s(:))
str=[str{:}]
AZ='A':'Z'
long=sum(ismember(str,AZ));
for k=1:numel(AZ)
freq(k,1)=100*sum(ismember(str,AZ(k)))/long
end

その他の回答 (3 件)

Mounic Kumar
Mounic Kumar 2019 年 6 月 25 日
function charnum = char_counter(fname,A)
fid = fopen(fname,'rt');
if fid < 0
charnum = -1;
return
end
if fid >0 && ischar(A)
k=0;
oneread = fgets(fid);
while ischar(oneread)
k = k + count(oneread,A);
oneread = fgets(fid);
end
charnum = k;
else
charnum = -1;
end
fclose(fid);

Amit Dubey
Amit Dubey 2020 年 5 月 15 日
編集済み: Amit Dubey 2020 年 6 月 2 日
function n=char_counter(fname,character)
fid=fopen(fname,'rt');
if fid<0
n=-1;
return;
elseif ~ischar(character)
n=-1;
return;
end
end
c=0;
ol=fgets(fid);
while ischar(ol)
c=c+count(ol,character);
ol=fgets(fid);
end
n=c;
fclose(fid);
  2 件のコメント
Walter Roberson
Walter Roberson 2020 年 5 月 15 日
If the file open works but ischar(character) fails, then you leave the file open when you return.
Amit Dubey
Amit Dubey 2020 年 6 月 2 日
Thank you, just made required modifications

サインインしてコメントする。


Priyamvada Shankar
Priyamvada Shankar 2019 年 3 月 23 日
編集済み: Priyamvada Shankar 2019 年 3 月 23 日
Please Help me with this ..function called char_counter that counts the number of a certain character in a text file. The function takes two input arguments, fname, a char vector of the filename and character, the char it counts in the file. The function returns charnum, the number of characters found. If the file is not found or character is not a valid char, the function return -1. As an example, consider the following run. The file "simple.txt" contains a single line: "This file should have exactly three a-s..."
  8 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 26 日
Why are you skipping down to the last line of the file?
Walter Roberson
Walter Roberson 2019 年 3 月 26 日
note: your function returns -1 if the character is valid but not found. Your function should only be returning -1 if the file is not found or if the input is not a valid scalar character.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by