【问题标题】:How to make a comparison between sentences and calculate the similarity?如何进行句子之间的比较并计算相似度?
【发布时间】:2021-03-30 02:22:31
【问题描述】:

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

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

Shell 脚本
Linux Shell 脚本
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 示例:

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

--

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

有人可以帮忙吗?

【问题讨论】:

  • 你能解释一下两个句子的联合“大小”相似度
  • The similarity 计算为两个句子之间单词交集的大小除以两个句子的并集大小:????????????=(????1∩????2)(????1∪????2)值为“0”表示两个句子完全不相似,“1”表示它们相同,0 和 1 之间的值表示相似程度。
  • 假设您想忽略您在上一个问题中列出的同一组单词,如示例代码所示,第二个示例中单词的并集大小为 6 (shell, script, or, bash, are, fun ),而不是 4,因此预期的输出应该是 0.166667,而不是 0.25

标签: linux bash shell unix command-line


【解决方案1】:

对我对your previous question 的回答稍作调整,仍将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多