필터 지우기
필터 지우기

Count number of words per row in a string

조회 수: 12 (최근 30일)
Angelavtc
Angelavtc 2022년 4월 21일
편집: Les Beckham 2022년 4월 21일
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!

채택된 답변

Image Analyst
Image Analyst 2022년 4월 21일
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

추가 답변 (2개)

Voss
Voss 2022년 4월 21일
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 2022년 4월 21일
편집: Les Beckham 2022년 4월 21일
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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by