Count number of words per row in a string

15 visualizaciones (últimos 30 días)
Angelavtc
Angelavtc el 21 de Abr. de 2022
Editada: Les Beckham el 21 de Abr. de 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!

Respuesta aceptada

Image Analyst
Image Analyst el 21 de Abr. de 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

Más respuestas (2)

Voss
Voss el 21 de Abr. de 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 el 21 de Abr. de 2022
Editada: Les Beckham el 21 de Abr. de 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

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by