Counting number of words and their characters
8 次查看(过去 30 天)
显示 更早的评论
oo
1 个评论
Stephen23
2021-10-24
Original question by Joe Ainsworth on 3rd Septempber 2021 retrieved from Google Cache:
Counting number of words and their characters
Hi all,
currenlty wirting a script which reads a text file, splits the lines into the individual words and stores the word lengths in an array.
i beleive this may be achieveable with a bag of words but it may not be neccessary or the simpliest way to do so.
print the total number of words, the number of characters within the words but dosesnt count spaces but does incude punctuation and the lengths of the individual words.
Needs to be outputted like so.
This file has zz words with bb characters
* Word x has yy characters
any insight is much appreciated
回答(1 个)
Ive J
2021-9-3
Maybe this help
txt = ["Why MATLAB doesn't offer much for data science?"; "Python and R beat MATLAB in ML"];
voc = tokenizedDocument(txt).Vocabulary;
len = arrayfun(@(x)numel(x{:}), voc);
% print document stat
wordn = voc + " has " + len + " characters";
fprintf('file txt has %d words with %d characters:\n', numel(voc), sum(len))
fprintf('\t%s\n', wordn.')
8 个评论
Ive J
2021-9-5
编辑:Ive J
2021-9-5
Well, seems you haven't Text Analytics Toolbox.
contains(struct2array(ver), 'Text Analytics Toolbox') % true is installed
In that case you can use a mixture of regexp and split to get the words. The challenge lies in punctuations. Consider my first example again:
txt = ["Why MATLAB (R2021) doesn't offer much for data science?!"; "Python and R, both beat MATLAB in ML."];
txt = join(txt, newline);
% replace the above lines with the following when reading from text files
% txt = string(fileread('myfile.txt'));
voc = unique(split(txt)); % we keep unique words, so each word is counted only once through the document.
% find punctuations
patt = regexpPattern('[^\w\s]');
punc = extract(txt, patt);
punc(punc == "'") = []; % keep apostrophes intact
voc = replace(voc, punc, ''); % remove punctuations from voc
voc = [voc; punc]; % merge all together
len = arrayfun(@(x)numel(x{:}), voc);
% print document stat
wordn = voc + " has " + len + " characters";
fprintf('file txt has %d words with %d characters:\n', numel(voc), sum(len))
fprintf('\t%s\n', wordn.')
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Statistics and Machine Learning Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!