algorithm - 返回文本之间亲和性的函数?

标签 algorithm text full-text-search relevance

考虑一下我有一个

string1 = "hello hi goodmorning evening [...]"

还有一些次要的关键词

compare1 = "hello evening"
compare2 = "hello hi"

我需要一个函数来返回文本和关键字之间的关联。示例:

function(string1,compare1);  // returns: 4
function(string1,compare2);  // returns: 5 (more relevant)

请注意,5 和 4 只是示例。

你可以说 - 写一个计算出现次数的函数 - 但对于这个例子,这是行不通的,因为两者都出现了 2 次,但 compare1 不太相关,因为在 string1 中没有准确找到“hello evening”(这两个词 hello和晚上比你好更遥远 hi)

有没有已知的算法可以做到这一点?

添加1:

在这种情况下,像“编辑距离”这样的算法将不起作用。 因为 string1 是一个完整的文本(比如 300-400 个单词),比较字符串最多 4-5 个单词。

最佳答案

一种动态规划算法

您要查找的内容似乎与 Smith–Waterman algorithm 非常相似做。

来自维基百科:

The algorithm was first proposed by Temple F. Smith and Michael S. Waterman in 1981. Like the Needleman-Wunsch algorithm, of which it is a variation, Smith-Waterman is a dynamic programming algorithm. As such, it has the desirable property that it is guaranteed to find the optimal local alignment with respect to the scoring system being used (which includes the substitution matrix and the gap-scoring scheme).

让我们看一个实际的例子,这样你就可以评估它的用处。

假设我们有一段文字:

text = "We the people of the United States, in order to form a more 
perfect union, establish justice, insure domestic tranquility, 
provide for the common defense, 

  promote the general welfare, 

  and secure the blessings of liberty to ourselves and our posterity, 
do ordain and establish this Constitution for the United States of 
America.";  

为了方便阅读,我将要匹配的部分隔离出来。

我们将比较相似性(或相似性)与字符串列表:

list = {
   "the general welfare",
   "my personal welfare",
   "general utopian welfare",
   "the general",
   "promote welfare",
   "stackoverflow rulez"
   };  

我已经实现了算法,所以我将计算相似度并对结果进行归一化:

sw = SmithWatermanSimilarity[ text, #] & /@ list;
swN = (sw - Min[sw])/(Max[sw] - Min[sw])  

然后我们绘制结果:

enter image description here

我认为这与您的预期结果非常相似。

喂!

一些实现(带源代码)

关于algorithm - 返回文本之间亲和性的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788344/

相关文章:

python - 我如何阅读特定行和该行下的 7 行

MySQL,文本索引不起作用

想要的算法 : Find all words of a dictionary that are similar to words in a free text

php - 使用日光浴室进行基本全文搜索

mysql - Lucene.NET索引实时更新

ruby-on-rails - 如何仅在使用 ElasticSearch 和 Tire 存在时按属性过滤搜索?

java - 使用优先级队列的 Dijkstra 算法

c++ - Lempel-Ziv-Welch 算法的解码问题

algorithm - 计算 1 <= k <= N 的 phi(k) 之和?

algorithm - 在 M 天内阅读 N 章书籍的最佳方式