How to find the exact location of a word in a string?

조회 수: 4 (최근 30일)
Yunfei Zhang
Yunfei Zhang 2016년 2월 13일
댓글: Guillaume 2016년 2월 13일
I have a string that 'chemical engineering is a challenge for electrical engineer'. I used to use 'strfind' function to find the exact location of the word‘engineer'. However, there is a problem that word engineering is also included in my results. How can i just get the location of word 'engineer' instead of 'engineering'.
list='chemical engineering is a challenge for electrical engineer';
temp=findstr(list,'engineer')
The result is
temp =
10 52

채택된 답변

Star Strider
Star Strider 2016년 2월 13일
This regexp call will pick up only ‘engineer’:
Str = 'chemical engineering is a challenge for electrical engineer';
idxs = regexp(Str, 'engineer\>')
idxs =
52
  댓글 수: 6
Guillaume
Guillaume 2016년 2월 13일
편집: Guillaume 2016년 2월 13일
You can prebuild the regular expressions before the loops if you wish.
word = strcat(word, '\>')
Yunfei Zhang
Yunfei Zhang 2016년 2월 13일
Thank you! It helps a lot for controlling the processing time as i also want to do the feature selection and clustering for my data.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2016년 2월 13일
편집: Guillaume 2016년 2월 13일
Another option, since the words you're trying to match are always delimited by spaces or the end of the sentence (other punctuation marks are already embedded in the words), is to add a space to the end of each word and to the end of each sentences. That way 'engineer ' does not match 'engineering ' anymore:
tic
docum = zeros(numel(pre), numel(word));
word2 = strcat(word, {' '}); %strcat removes trailing ' ' if it's not in a cell array
pre2 = strcat(vertcat(pre{:}), {' '}); %why is your pre a cell array of 1x1 cell arrays?
for widx = 1:numel(word)
docum(:, widx) = cellfun(@numel, strfind(pre2, word2{widx}));
end
toc
I'm not convinced it's going to be faster than regexp:
tic
docum = zeros(numel(pre), numel(word));
word2 = strcat(word, '\>');
pre2 =vertcat(pre{:}); %why is your pre a cell array of 1x1 cell arrays?
for widx = 1:numel(word)
docum(:, widx) = cellfun(@numel, regexp(pre2, word2{widx}));
end
toc
In my testing they take both more or less the same time.
  댓글 수: 3
Star Strider
Star Strider 2016년 2월 13일
@Guillaume — Thank you. I had to be away for a few minutes.
Guillaume
Guillaume 2016년 2월 13일
@Yunfei, what is probably having the most effect on the processing speed is that I apply the regexp or strfind to all the sentences at once. There is only one loop, looping over the individual words.

댓글을 달려면 로그인하십시오.

카테고리

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