首页 > 解决方案 > 如何进行句子之间的比较并计算相似度?

问题描述

如何将第二句的第一句与第一句与第三句等进行比较,并使用shell script或计算相似度bash

我有一个包含重复单词的句子,例如文件中的输入数据,my_text.txt 并且应该忽略每个句子的重复单词、填充词和非字母字符。

Shell Script
Linux Shell Script
Shell 或 bash 很有趣

我用这个 shell 脚本来寻找相似之处

  words=$(
  < my_text.txt tr 'A-Z' 'a-z' |
  grep -Eon '\b[a-z]*\b' |
  grep -Fwvf <(printf %s\\n is a to be by the and for) |
  sort -u | cut -d: -f2 | sort
  )
  union=$(uniq <<< "$words" | wc -l)
  intersection=$(uniq -d <<< "$words" | wc -l)
  echo "similarity is $(bc -l <<< "$intersection/$union")"

上面的脚本一次计算所有句子的相似度,但我想找到所有相似度对(例如 1:2、1:3、1:4、...、2:3、2:4、...、3:4 , ...)

我想找到这样的相似性 2 示例:

--

有人可以帮忙吗?

标签: linuxbashshellunixcommand-line

解决方案


对我对您之前的问题的回答稍作调整,仍将 GNU awk 用于 FPAT 和数组数组:

$ cat tst.awk
BEGIN {
    split("is a to be by the and for",tmp)
    for (i in tmp) {
        stopwords[tmp[i]]
    }
    FPAT="[[:alnum:]_]+"
}
{
    for (i=1; i<=NF; i++) {
        word = tolower($i)
        if ( !(word in stopwords) ) {
            words[NR>1?2:1][word]
        }
    }
}
NR > 1 {
    numCommon = 0
    for (word in words[1]) {
        if (word in words[2]) {
            numCommon++
        }
    }
    totWords = length(words[1]) + length(words[2]) - numCommon
    print (totWords ? numCommon / totWords : 0)
    delete words[2]
}

$ awk -f tst.awk file
0.666667
0.166667

推荐阅读