Effacer les filtres
Effacer les filtres

Count number of words per row in a string

12 vues (au cours des 30 derniers jours)
Angelavtc
Angelavtc le 21 Avr 2022
Modifié(e) : Les Beckham le 21 Avr 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!

Réponse acceptée

Image Analyst
Image Analyst le 21 Avr 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

Plus de réponses (2)

Voss
Voss le 21 Avr 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 le 21 Avr 2022
Modifié(e) : Les Beckham le 21 Avr 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

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by