Counting the number of a specific word in text.

8 ビュー (過去 30 日間)
pawlo392
pawlo392 2019 年 5 月 13 日
コメント済み: Guillaume 2019 年 5 月 13 日
I want to create a program, tah will count specific words in text. I wrote this:
filename='File name : ';
word= 'Searched word : ';
A=input(filename,'s');
B=input(word,'s');
count=0;
fid=fopen(filename);
C=textscan(fid,'%/s');
for i=1:lenght(C{1})
words=char(C{1}(i));
words=strrep(words,'.','');
words=strrep(words,',','');
if (strcmp(words,word))
count=count+1;
end
end
But this program isn't working.
I got:
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in count_word (line 7)
C=textscan(fid,'%/s'
  3 件のコメント
pawlo392
pawlo392 2019 年 5 月 13 日
編集済み: pawlo392 2019 年 5 月 13 日
Ok, I didn't see this:
fid=fopen(filename);
Should be:
fid=fopen(A);
But, Now I got:
Error using textscan
Unable to parse the format character vector at position 1 ==> %/s
Unsupported format specifier '%/'. See the documentation for TEXTSCAN for
supported formats.
Guillaume
Guillaume 2019 年 5 月 13 日
Well, yes as the error message says, %/s is not a valid format specifier. The / has no place there.

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

採用された回答

Jan
Jan 2019 年 5 月 13 日
編集済み: Jan 2019 年 5 月 13 日
Use uigetfile instead of an fragile input command. But even then you should check the output of fopen:
[fid, msg] = fopen(filename);
assert(fid ~= -1, 'Cannot open file %s: %s', filename, msg);
Instead of using the cells created by textscan, the import as char vector is easier:
[filename, pathname] = uigetfile;
file = fullfile(filepath, filename);
word = input('Searched word : ', 's');
str = fileread(file);
str(ismember(str, '.,:!"''?')) = ' '; % Replace punctuation
str = [' ', str, ' '];
match = strfind(str, [' ', word, ' ']);
count = numel(match);

その他の回答 (1 件)

Image Analyst
Image Analyst 2019 年 5 月 13 日
Instead of
A=input(filename,'s');
try this:
[folder, baseFileName] = uigetfile('*.*');
filename = fullfile(folder, baseFileName)

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by