c++ - 如何调整 Levenshtein 距离算法以将匹配限制为单个单词?

标签 c++ algorithm stdstring levenshtein-distance heuristics

我在 C++ 中使用 Levenshtein 距离算法来比较两个字符串以衡量它们彼此之间的接近程度。然而,普通的 Levenshtein Distance 算法不区分由空格分隔的单词边界。这导致比我想要的更小的距离计算。我正在比较标题以查看它们彼此之间的接近程度,我希望算法不会将来自多个单词的字符计为匹配字符。

例如,如果我比较这两个字符串,我会得到以下结果,+ 表示匹配,- 表示不匹配:

Al Chertoff Et
Al Church Department of finance Et
+++++------+--++-----++-+------+++
Al Ch      e  rt     of f       Et

我得到 20 的距离,单词 "Chertoff" 匹配四个单词 "Church Department of finance" 而我真的希望它们是通过不允许字符与多个单词匹配并与单词 “Chertoff” 最匹配一个单词 “Department” 获得 25 的距离来考虑彼此更远>,三个字符匹配:

Al Chertoff Et
Al Church Department of finance Et
+++--------+--++---------------+++
Al         e  rt                Et
         Ch     off

我如何调整 Levenshtein 距离来完成此操作,或者是否有其他距离算法更适合此操作?也许对每个单词单独使用 Levenshtein 距离并选择距离最小的单词?但是,如果将一个词很好地匹配到字符串的深处会导致后续词匹配不佳,因为它们的匹配最好出现在字符串的较早位置?这可以通过调整为单词级别的 Levenshtein 距离以某种方式完成吗?

例如,对于下面这个更复杂的例子,这个思路的最短距离是20:

Al Chertoff Deport Et
Al Church Department of finance Et
+++++----++++-++---------------+++
Al Ch     Dep rt                Et
     ertoff  o

而不是最大化 "Chertoff" 的匹配并获得更长的距离 24:

Al Chertoff Deport Et
Al Church Department of finance Et
+++--------+--++-----+---------+++
Al         e  rt     o          Et
         Ch     off
                  Dep rt

我目前对 Levenshtein 距离的实现如下:

size_t
levenshtein_distance(const std::string& a_compare1,
                     const std::string& a_compare2) {
  const size_t length1 = a_compare1.size();
  const size_t length2 = a_compare2.size();
  std::vector<size_t> curr_col(length2 + 1);
  std::vector<size_t> prev_col(length2 + 1);

  // Prime the previous column for use in the following loop:
  for (size_t idx2 = 0; idx2 < length2 + 1; ++idx2) {
    prev_col[idx2] = idx2;
  }

  for (size_t idx1 = 0; idx1 < length1; ++idx1) {
    curr_col[0] = idx1 + 1;

    for (size_t idx2 = 0; idx2 < length2; ++idx2) {
      const size_t compare = a_compare1[idx1] == a_compare2[idx2] ? 0 : 1;

      curr_col[idx2 + 1] = std::min(std::min(curr_col[idx2] + 1,
                                             prev_col[idx2 + 1] + 1),
                                    prev_col[idx2] + compare);
    }

    curr_col.swap(prev_col);
  }

  return prev_col[length2];
}

最佳答案

通过使 levenshtein_distance 成为序列容器上的通用算法并包括计算两个元素之间距离的成本函数,我可以非常接近您想要的结果:

template<typename T, typename C>
size_t
seq_distance(const T& seq1, const T& seq2, const C& cost,
             const typename T::value_type& empty = typename T::value_type()) {
  const size_t size1 = seq1.size();
  const size_t size2 = seq2.size();

  std::vector<size_t> curr_col(size2 + 1);
  std::vector<size_t> prev_col(size2 + 1);

  // Prime the previous column for use in the following loop:
  prev_col[0] = 0;
  for (size_t idx2 = 0; idx2 < size2; ++idx2) {
    prev_col[idx2 + 1] = prev_col[idx2] + cost(empty, seq2[idx2]);
  }

  for (size_t idx1 = 0; idx1 < size1; ++idx1) {
    curr_col[0] = curr_col[0] + cost(seq1[idx1], empty);

    for (size_t idx2 = 0; idx2 < size2; ++idx2) {
      curr_col[idx2 + 1] = std::min(std::min(
        curr_col[idx2] + cost(empty, seq2[idx2]),
        prev_col[idx2 + 1] + cost(seq1[idx1], empty)),
        prev_col[idx2] + cost(seq1[idx1], seq2[idx2]));
    }

    curr_col.swap(prev_col);
    curr_col[0] = prev_col[0];
  }

  return prev_col[size2];
}

给定上面的seq_distance,两个句子之间的编辑距离使得不能在词边界之间进行编辑,可以定义如下:

size_t
letter_distance(char letter1, char letter2) {
  return letter1 != letter2 ? 1 : 0;
}

size_t
word_distance(const std::string& word1, const std::string& word2) {
  return seq_distance(word1, word2, &letter_distance);
}

size_t
sentence_distance(const std::string& sentence1, const std::string& sentence2) {
  std::vector<std::string> words1;
  std::vector<std::string> words2;
  std::istringstream iss1(sentence1);
  std::istringstream iss2(sentence2);
  std::copy(std::istream_iterator<std::string>(iss1),
            std::istream_iterator<std::string>(),
            std::back_inserter(words1));
  std::copy(std::istream_iterator<std::string>(iss2),
            std::istream_iterator<std::string>(),
            std::back_inserter(words2));
  return seq_distance(words1, words2, &word_distance);
}

这是处理 ideone 的代码.我已经测试了几个案例,我很确定它做的是正确的,但你应该多尝试一下以确保结果是合理的。

请注意,这不完全是您要求的,因为它忽略了编辑距离测量中的所有空格:我认为修改它不应该太难,但我没想到通过完全。无论如何,这可能同样好(甚至更好),具体取决于您的需要,所以我会让您决定是否要尝试调整它。

请注意,您的原始代码在以下两行中略有错误:

curr_col.reserve(length2 + 1);
prev_col.reserve(length2 + 1);

在 vector 中保留容量,但实际上并不改变它们的大小,因此之后访问数组是未定义的行为。如果您要访问一个范围内的元素,您实际上应该调整 vector :reserve通常用于您即将push_back的情况一定数量的元素一个一个地增加(随着你的移动增加大小,而不是一次全部增加)并且你想避免多次内部重新分配的成本(因为每次容量增加时内部容量只增加一个特定的因素超过)。

编辑:

This version将单词之间的空格作为编辑距离的一部分考虑在内,但结果仍然与您的示例不完全相同,因为在某些情况下需要添加多个空格。

关于c++ - 如何调整 Levenshtein 距离算法以将匹配限制为单个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416798/

相关文章:

c++ - 模板而非 g++ 的 MSVC 重载错误

python - 欧式距离的高效计算

c++ - 取消继承 std::basic_string

c++ - 依赖于另一个库的库上的 CMake 和 target_link_libraries

c++ - Heap/C++ 标准库使用 Under Green Hills INTEGRITY

c++ - 指针内存分配问题

algorithm - 如何在集群中运行的节点中选举主节点?

algorithm - 生成边分布均匀的随机图

c++ - std::string 分配策略

c++ - 在C++中递归地从十进制到八进制。以std::string格式输出