gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:00:08 24 4
gpt4 key购买 nike

如何用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com