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

Sam*_*shi 1 string matlab compare extract

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

Div*_*kar 5

使用intersectstrsplit用于一行代码-

common_word = intersect(strsplit(string1),strsplit(string2))
Run Code Online (Sandbox Code Playgroud)

strsplit将每个字符串拆分为单词单元,然后intersect找出共同的字符串。

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

common_word =intersect(regexp(string1,'\s','Split'),regexp(string2,'\s','Split'))
Run Code Online (Sandbox Code Playgroud)

奖励:从常用词中删除停用词

让我们添加stop-words这两个字符串的共同点-

string1 = 'hello my name is bob and I am going to the zoo'
string2 = 'today bob went to the park'
Run Code Online (Sandbox Code Playgroud)

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

common_word = 
    'bob'    'the'    'to'
Run Code Online (Sandbox Code Playgroud)

现在,这些词- 'the''to'是停用词的一部分。如果你想有其删除,让我提出这一点- Removing stop words from single string它的接受的解决方案

最终的输出将是'bob',您正在寻找谁!

  • @SamiyaQureshi-从R2013a开始,`strsplit`才引入MATLAB。之所以对您“不是命令”,是因为您使用的是R2013a之前的MATLAB版本。使用`regexp`是模仿`strsplit`在做什么的方法。BTW +1为您Divakar! (3认同)