How to find the exact location of a word in a string?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
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
Plus de réponses (1)
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
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.
Voir également
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!