What is the code to count the number of word in the text file?

14 ビュー (過去 30 日間)
gogogo
gogogo 2022 年 4 月 14 日
コメント済み: Rik 2022 年 4 月 14 日
I just what to know the code.
  1 件のコメント
Rik
Rik 2022 年 4 月 14 日
As Scott hints at: there are several definitions of what would constitute. If precision matters, you will have to define what you require, which will depend on the language as well.
E.g.: is 'ex-smoker' one word or two? What about 'you're'?
Try to come up with counter-examples that would break your defenition.

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

回答 (1 件)

Scott MacKenzie
Scott MacKenzie 2022 年 4 月 14 日
編集済み: Scott MacKenzie 2022 年 4 月 14 日
There are a few ways to set this up. Here's one using line-by-line processing and a loose definition of a word as a space-deliminited sequence of characters.
fileName = 'example.txt'; % any text file
fid = fopen(fileName);
n = 0;
while ~feof(fid)
line = fgetl(fid);
line = string(line);
s = split(line);
n = n + length(s);
end
fclose(fid);
fprintf('Number of words: %d\n', n);
You can also process the entire text file at once:
fileName = 'example.txt'; % any text file
fid = fopen(fileName);
C = textscan(fid, '%s');
fclose(fid);
s = string(C{:});
fprintf('Number of words: %d\n', length(s));
If you have the Text Analytics Toolbox, there are more possibilities using more sophisticated concepts of a "word".

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by