Count number of words per row in a string

14 Ansichten (letzte 30 Tage)
Angelavtc
Angelavtc am 21 Apr. 2022
Bearbeitet: Les Beckham am 21 Apr. 2022
Say I have the following text:
str = [
"an example of a short sentence"
"a second short sentence"]
I would like to count the total number of words per row.
In this case, I want matlab to tell me: 6, 4
I have tried the "count" command, but it is only meant to find specific words.
Thanks for your help!

Akzeptierte Antwort

Image Analyst
Image Analyst am 21 Apr. 2022
Try this:
str = [...
"an example of a short sentence" ;
"a second short sentence"]
counts = zeros(size(str));
for row = 1 : length(str)
counts(row) = length(strsplit(str(row)));
end

Weitere Antworten (2)

Voss
Voss am 21 Apr. 2022
I won't claim that this is the best way to do it, or that it'll work for anything you want to consider a "word" in your string array, but here's something:
str = [
"an example of a short sentence"
"a second short sentence"];
arrayfun(@(x)numel(strsplit(x)),str)
ans = 2×1
6 4

Les Beckham
Les Beckham am 21 Apr. 2022
Bearbeitet: Les Beckham am 21 Apr. 2022
In 2020b or later you can also use a pattern with a regex pattern to find (and count) words. It took some experimenting to get this right but it works.
str = [
"an example of a short sentence"
"a second short sentence"];
count(str, regexpPattern('\w*'))
ans = 2×1
6 4
If you don't want to allow underscores and numbers in your "words", use this. This allows one optional capital letter only at the beginning of the words.
count(str, regexpPattern('[A-Z]?[a-z]*'))
ans = 2×1
6 4

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by