一、问题描述
需要匹配多个类似的内容,并且要求相似度在70%以上并且长度相近,可以在处理每个匹配项时,将其与所有目标进行比较,并筛选出符合条件的匹配项。
二、代码
using System;
using System.Collections.Generic;
using System.Linq;
// 定义页面名称
string pageTitle = "大气压力";
// 定义要匹配的内容列表
List<string> targetDescriptions = new List<string>
{
"大气层压力",
"天上的大气层压力",
"压力大气层"
};
// 计算字符串相似度
double CalculateSimilarity(string s1, string s2)
{
int maxLength = Math.Max(s1.Length, s2.Length);
int distance = LevenshteinDistance(s1, s2);
return 1.0 - (double)distance / maxLength;
}
// 计算Levenshtein距离
public int LevenshteinDistance(string word1, string word2)
{
int m = word1.Length;
int n = word2.Length;
if (m * n == 0)
{
return Math.Max(m, n);
}
int[,] lev = new int[m + 1, n + 1];
// 字符串word1从空串变为字符串word2前j个字符的莱文斯坦距离
for (int j = 0; j < n + 1; j++)
{
lev[0, j] = j;
}
// 字符串word1从前i个字符变为空串的莱文斯坦距离
for (int i = 0; i < m + 1; i++)
{
lev[i, 0] = i;
}
for (int i = 1; i < m + 1; i++)
{
for (int j = 1; j < n + 1; j++)
{
// 在字符串word1的前i个字符与字符串word2的前j-1个字符完全相同的基础上, 进行一次插入操作
int countByInsert = lev[i, j - 1] + 1;
// 在字符串word1的前i-1个字符与字符串word2的前j个字符完全相同的基础上, 进行一次删除操作
int countByDel = lev[i - 1, j] + 1;
// 在字符串word1的前i-1个字符与字符串word2的前j-1个字符完全相同的基础上, 进行一次替换操作
int countByReplace = word1[i - 1] == word2[j - 1] ? lev[i - 1, j - 1] : lev[i - 1, j - 1] + 1;
// 计算字符串word1的前i个字符与字符串word2的前j个字符的莱文斯坦距离
lev[i, j] = Math.Min(countByInsert, Math.Min(countByDel, countByReplace));
}
}
return lev[m, n];
}
// 遍历所有要匹配的内容
foreach (string targetDescription in targetDescriptions)
{
// 检查文本与页面名称的相似度和长度
if (CalculateSimilarity(targetDescription, pageTitle) >= 0.7 && Math.Abs(targetDescription.Length - pageTitle.Length) <= 3)
{
Console.WriteLine("匹配成功: " + targetDescription);
}
}
三、解释
- 首先,定义了一个页面名称pageTitle为"大气压力"。
- 然后,定义了一个要匹配的内容列表targetDescriptions,包含了三个待匹配的描述
- 接着,定义了一个CalculateSimilarity函数,用于计算两个字符串之间的相似度。在函数内部,首先计算两个字符串的最大长度,然后使用Levenshtein距离算法计算它们之间的编辑距离,最后返回相似度值。
- 紧接着,定义了一个LevenshteinDistance函数,用于计算两个字符串之间的Levenshtein距离。该函数通过动态规划算法计算两个字符串之间的编辑距离。
- 最后,通过遍历要匹配的内容列表targetDescriptions,对每个描述进行相似度和长度的检查。如果某个描述与页面名称的相似度大于等于0.7并且长度差值不超过3,则输出"匹配成功:"以及匹配的描述内容。