比较两个字符串并提取常用字

时间:2014-08-15 16:14:52

标签: string matlab compare extract

在MATLAB中,我们如何比较2个字符串并打印出常用字。例如string1 =“你好我的名字是鲍勃”;和string2 =“今天鲍勃去了公园”;鲍勃这个词在两​​者中都很常见。要遵循的结构是什么。

2 个答案:

答案 0 :(得分:4)

intersect strsplit 一起使用 -

common_word = intersect(strsplit(string1),strsplit(string2))

strsplit将每个字符串拆分为单词格,然后intersect找到常用字符串。

如果您想避免strsplit,可以使用regexp代替 -

common_word =intersect(regexp(string1,'\s','Split'),regexp(string2,'\s','Split'))

加分:从常用词中删除停用词

让我们添加一些这两个字符串共有的stop-words -

string1 = 'hello my name is bob and I am going to the zoo'
string2 = 'today bob went to the park'

使用前面介绍的解决方案,您将获得 -

common_word = 
    'bob'    'the'    'to'

现在,这些词语'the''to'是停止词的一部分。如果你想删除它们,请让我建议一下 - Removing stop words from single string  和it's accepted solution

最终输出为'bob',您正在寻找它!

答案 1 :(得分:2)

如果您只查找匹配的单词,用空格分隔,您可以使用strsplit将每个字符串更改为单词的单元格数组,然后循环搜索每个字符串。

str1 = 'test if this works';
str2 = 'does this work?';
cell1 = strsplit(str1);
cell2 = strsplit(str2);
for n = 1:length(cell1)
    for m = 1:length(cell2)
    if strcmp(cell1{n},cell2{m})
        disp(cell1{n});
    end
    end
end

请注意,在我的示例中,cell2的最后一个成员是'工作?'因此,如果您的字符串中有标点符号,则必须对其进行检查(isletter可能会有所帮助)。