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

4 vues (au cours des 30 derniers jours)
Yunfei Zhang
Yunfei Zhang le 13 Fév 2016
Commenté : Guillaume le 13 Fév 2016
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

Réponse acceptée

Star Strider
Star Strider le 13 Fév 2016
This regexp call will pick up only ‘engineer’:
Str = 'chemical engineering is a challenge for electrical engineer';
idxs = regexp(Str, 'engineer\>')
idxs =
52
  6 commentaires
Guillaume
Guillaume le 13 Fév 2016
Modifié(e) : Guillaume le 13 Fév 2016
You can prebuild the regular expressions before the loops if you wish.
word = strcat(word, '\>')
Yunfei Zhang
Yunfei Zhang le 13 Fév 2016
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.

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 13 Fév 2016
Modifié(e) : Guillaume le 13 Fév 2016
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 commentaires
Star Strider
Star Strider le 13 Fév 2016
@Guillaume — Thank you. I had to be away for a few minutes.
Guillaume
Guillaume le 13 Fév 2016
@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.

Connectez-vous pour commenter.

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