linux - 如何在句子之间进行比较并计算相似度?

标签 linux bash shell unix command-line

如何用shell script or bash 来比较第一句第二句和第一句与第三句等等,并计算相似度>

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

Shell Script
Linux Shell Script
Shell or bash are fun

我用这个 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 个例子的相似性:

  • 第一句和第二句:
  • 两个句子的交集:Shell + Script
  • 两个句子的联合“大小”:3
  • 相似度:0.66666666

--

  • 第一句和第三句:
  • 两个句子的交集:Shell
  • 两个句子的联合“大小”:4
  • 相似度:0.25

有人可以帮忙吗?

最佳答案

我对 your previous question 的回答稍作调整,仍然对 FPAT 和数组的数组使用 GNU awk:

$ 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

关于linux - 如何在句子之间进行比较并计算相似度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373832/

相关文章:

linux - 我如何在 shell 中使用函数编写这个

linux - 过滤掉两个文件之间的内容

python - 单击终端中的元素

c++ - linux C++ xlib,处理器速度快吗?

php - 批量清除php入侵的Bash脚本

javascript - 通过URL获取执行本地bash脚本

linux - 将几个页面作为大区域映射到进程内存空间

c++ - 如何在 Linux 中优化构建

bash - 在 bash 中使用管道缓冲来自串行设备的数据

linux - 如何在 unix 中只删除 > [大于] 和 < [小于] 之间的一个换行符