How do I compare two sentences with similar words?

11 ビュー (過去 30 日間)
Prajwal Venkatesh
Prajwal Venkatesh 2020 年 1 月 20 日
編集済み: Adam Danz 2020 年 1 月 20 日
I have two string sentences with similar words, I want to know if there is a common word between them, case insensitive.
string1='Install peoplenet antenna';
string2='ANT-PMG,PEOPLENET,30';
So I want the answer to be 'true' or logical because 'peoplenet' is there in both the sentences.

採用された回答

Sindar
Sindar 2020 年 1 月 20 日
First, split each sentence into the individual words
words_1 = split(string1,[" ",","]);
words_2 = split(string2,[" ",","]);
Then check if they share any words (comparing lowercase versions)
common_words = intersect(lower(words_1),lower(words_2))
share_words = ~isempty(common_words);
  3 件のコメント
Sindar
Sindar 2020 年 1 月 20 日
編集済み: Sindar 2020 年 1 月 20 日
Yup, agreed that yours is more robust in that case. If you know the delimiters, mine might be better (is "ANT-PMG" one word or two? What about "30" or "John's"?).
(It looks like I was typing when you submitted your answer. Otherwise, I would have just commented on it instead of creating a separate near-duplicate answer)
Adam Danz
Adam Danz 2020 年 1 月 20 日
Not a problem - different approaches listed in the answers section is often helpful.

サインインしてコメントする。

その他の回答 (1 件)

Adam Danz
Adam Danz 2020 年 1 月 20 日
編集済み: Adam Danz 2020 年 1 月 20 日
I wouldn't be surprised if a more robust algorithm already exists but this simple appraoch takes the following steps.
  1. Replace the non-letters with empty spaces {, . ; ( 0 - etc... }
  2. Converts all characters to lower case
  3. Splits the strings into words
  4. Detects if there are matching words.
isMatch is the logical output that identifies if there is a match or not.
string1='Install peoplenet antenna';
string2='ANT-PMG,PEOPLENET,30';
% replace non-letters with a space and convert to lower case.
str1 = lower(string1);
str2 = lower(string2);
str1(~isstrprop(str1,'alpha')) = ' ';
str2(~isstrprop(str2,'alpha')) = ' ';
% Split the strings into words
words1 = strsplit(str1);
words2 = strsplit(str2);
% Detect matches
isMatch = any(ismember(words1, words2));
% Note, the following line will show which words were similar
% ismember(words1, words2)
  1 件のコメント
Prajwal Venkatesh
Prajwal Venkatesh 2020 年 1 月 20 日
Great!
Thanks a lot!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by