如何匹配两个字符串之间的某些单词(在MATLAB中)?

时间:2014-03-13 15:16:55

标签: arrays matlab match words stop-words

在以下两个字符串中,单词'rabbit'和'tree'匹配:

str1 = ('rabbit is eating grass near a tree');
str2 = ('rabbit is sleeping under tree');

假设cmp是声明要比较两者的变量。我希望结果为:

cmp = 2

或显示两个单词匹配的内容。我该怎么做?

5 个答案:

答案 0 :(得分:4)

根据另一个答案,将字符串拆分为一个独特单词的单元格数组。

str1= ('rabbit is eating grass near a tree');
str2= ('rabbit is sleeping under tree');

% split string into cell array of unique strings
split1 = regexp(str1,'\s','Split');
split2 = regexp(str2,'\s','Split');

或者,MATLAB的更新版本(IIRC R2013a)包含一个strsplit()函数,因此可以将拆分缩小为

split1 = strsplit(str1);
split2 = strsplit(str2);

然后使用intersect()函数获取两个单元格数组之间的公共元素数。添加长度以返回整数计数。

cmp = length(intersect(split1,split2));

答案 1 :(得分:2)

我假设他们匹配的位置或顺序没有限制。首先,您需要将句子拆分为单个单词,删除任何重复单词,然后查看句子2中的任何单词是否与第一个句子中的单词匹配。

现在如果排序确实很重要,那就不那么简单了,但是你的问题没有表明这种限制

str1= ('rabbit is eating grass near a tree');
str2= ('rabbit is sleeping under tree');
split1 = unique(regexp(str1,'\s','Split'));
split2 = unique(regexp(str2,'\s','Split'));

% Storing all words in the first sentence into a map for quick search/access
dict = containers.Map();
for ii = 1:numel(split1)
   dict(split1{ii}) = true; 
end

% create temp holding cell array, then loop through, looking to see if 
% any word in the second sentence is stored in the dictionary made from
% the first sentence. 
matches = {};
for jj = 1:numel(split2)
    if dict.isKey(split2{jj})
        matches = [matches,split2{jj}]; % not best but length initially unknown
    end
end

numMatches = numel(matches) % return the number of matches

变量matches将包含两个句子之间匹配的所有单词。

答案 2 :(得分:2)

使用ismember,您只需要一行。

str1 = ('rabbit is eating grass near a tree');
str2 = ('rabbit is sleeping under a tree');

result = sum( ismember( strsplit(str1), strsplit(str2) ) )

result =

    4               %// I included also the article "a"

请注意,对于以下句子,结果是相同的:

str1 = ('rabbit is eating grass near a tree, an oak tree');
str2 = ('rabbit is sleeping under a tree and is dreaming about a tree');

result = sum( ismember( strsplit(str1), strsplit(str2) ) )

MZimmerman6建议不要提前删除重复项。


如果要过滤不需要的字符串的结果,可以引入另一个字符串的单元格数组,但所有例外情况都是:

str3 = {'is','a'}
unwanted = sum( ismember( intersect( strsplit(str1), strsplit(str2) ), str3 ) )

unwanted =

     2

总之它看起来像是:

str1 = ('rabbit is eating grass near a tree, an oak tree');
str2 = ('rabbit is sleeping under a tree and is dreaming about a tree');
str3 = {'is','a'}

[x,y,z] = deal( strsplit(str1), strsplit(str2), str3 )
result = sum(ismember(x,y)) - sum(ismember(intersect(x,y),z))
       =       4            -            2           =        2

答案 3 :(得分:2)

"疯狂" bsxfun方法,可能类似于intersect,但未经过测试 -

功能 -

function out = cell2_matchind(split1,split2)

c1 = char(split1)-'0';
c2 = char(split2)-'0';
if size(c1,2)<size(c2,2)
    c1 = [c1 -16.*ones(size(c1,1),size(c2,2)-size(c1,2))];
else
    c2 = [c2 -16.*ones(size(c2,1),size(c1,2)-size(c2,2))];
end
out = any(squeeze(sum(bsxfun(@eq,permute(c1,[3 2 1]),c2),2))==size(c2,2),2);

主要MATLAB脚本 -

% Source of stopwords- http://norm.al/2009/04/14/list-of-english-stop-words/
stopwords_cellstring={'a', 'about', 'above', 'above', 'across', 'after', ...
    'afterwards', 'again', 'against', 'all', 'almost', 'alone', 'along', ...
    'already', 'also','although','always','am','among', 'amongst', 'amoungst', ...
    'amount',  'an', 'and', 'another', 'any','anyhow','anyone','anything','anyway', ...
    'anywhere', 'are', 'around', 'as',  'at', 'back','be','became', 'because','become',...
    'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below',...
    'beside', 'besides', 'between', 'beyond', 'bill', 'both', 'bottom','but', 'by',...
    'call', 'can', 'cannot', 'cant', 'co', 'con', 'could', 'couldnt', 'cry', 'de',...
    'describe', 'detail', 'do', 'done', 'down', 'due', 'during', 'each', 'eg', 'eight',...
    'either', 'eleven','else', 'elsewhere', 'empty', 'enough', 'etc', 'even', 'ever', ...
    'every', 'everyone', 'everything', 'everywhere', 'except', 'few', 'fifteen', 'fify',...
    'fill', 'find', 'fire', 'first', 'five', 'for', 'former', 'formerly', 'forty', 'found',...
    'four', 'from', 'front', 'full', 'further', 'get', 'give', 'go', 'had', 'has', 'hasnt',...
    'have', 'he', 'hence', 'her', 'here', 'hereafter', 'hereby', 'herein', 'hereupon', ...
    'hers', 'herself', 'him', 'himself', 'his', 'how', 'however', 'hundred', 'ie', 'if',...
    'in', 'inc', 'indeed', 'interest', 'into', 'is', 'it', 'its', 'itself', 'keep', 'last',...
    'latter', 'latterly', 'least', 'less', 'ltd', 'made', 'many', 'may', 'me', 'meanwhile',...
    'might', 'mill', 'mine', 'more', 'moreover', 'most', 'mostly', 'move', 'much', 'must',...
    'my', 'myself', 'name', 'namely', 'neither', 'never', 'nevertheless', 'next', 'nine',...
    'no', 'nobody', 'none', 'noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of', 'off',...
    'often', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise',...
    'our', 'ours', 'ourselves', 'out', 'over', 'own','part', 'per', 'perhaps', 'please',...
    'put', 'rather', 're', 'same', 'see', 'seem', 'seemed', 'seeming', 'seems', 'serious',...
    'several', 'she', 'should', 'show', 'side', 'since', 'sincere', 'six', 'sixty', 'so',...
    'some', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhere', ...
    'still', 'such', 'system', 'take', 'ten', 'than', 'that', 'the', 'their', 'them',...
    'themselves', 'then', 'thence', 'there', 'thereafter', 'thereby', 'therefore', ...
    'therein', 'thereupon', 'these', 'they', 'thickv', 'thin', 'third', 'this', 'those',...
    'though', 'three', 'through', 'throughout', 'thru', 'thus', 'to', 'together', 'too',...
    'top', 'toward', 'towards', 'twelve', 'twenty', 'two', 'un', 'under', 'until', 'up',...
    'upon', 'us', 'very', 'via', 'was', 'we', 'well', 'were', 'what', 'whatever', 'when',...
    'whence', 'whenever', 'where', 'whereafter', 'whereas', 'whereby', 'wherein',...
    'whereupon', 'wherever', 'whether', 'which', 'while', 'whither', 'who', 'whoever',...
    'whole', 'whom', 'whose', 'why', 'will', 'with', 'within', 'without', 'would', 'yet',...
    'you', 'your', 'yours', 'yourself', 'yourselves', 'the'};

str1 = ('rabbit is eating grass near a tree and will be sleeping inside the tree-hole');
str2 = ('rabbit is sleeping under tree and after waking up will be eating the nuts nearby');

split1 = unique(regexp(str1,'\s','Split'),'stable');
split2 = unique(regexp(str2,'\s','Split'),'stable');

cw_split2 = split2(cell2_matchind(split1,split2))
cw_split2_nostopwd = cw_split2(~cell2_matchind(stopwords_cellstring,cw_split2))
cmp = numel(cw_split2_nostopwd)

输出 -

cw_split2 = 
    'rabbit'    'is'    'sleeping'    'tree'    'and'    'will'    'be'    'eating'    'the'

cw_split2_nostopwd = 
    'rabbit'    'sleeping'    'tree'    'eating'

cmp =
     4

答案 4 :(得分:0)

用于不区分大小写;

CMP = strcmpi(string,string)

将此用于区分大小写;

CMP = strcmpi(string,string)

如果CMP为1,如果为0则它们是相同的。

如果您不想要空格,这样可以更好地进行比较,请先修剪它们并进行比较。

修剪;

newString = strtrim(str)