是否有一种哈希算法可以为相似单词生成类似的数字值?我想可能会有许多误判,但这似乎对于搜索修剪可能是有用的。
编辑:Soundex很不错,可能会派上用场,但理想情况下,我希望有一些行为类似于这样的东西:abs(f('horse') - f('hoarse')) < abs(f('horse') - f('goat'))
在维基百科上查看Soundex算法,您还没有指定一种语言,但那里有多种语言的示例实现链接。显然,这会为类似发音的单词提供相同的字符串哈希值,但是您可以应用Boost.Hash中使用的字符串->整数哈希方法来获得整数。
编辑:为了澄清,这是一个C ++实现的示例...
#include <boost/foreach.hpp>
#include <boost/functional/hash.hpp>
#include <algorithm>
#include <string>
#include <iostream>
char SoundexChar(char ch)
{
switch (ch)
{
case 'B':
case 'F':
case 'P':
case 'V':
return '1';
case 'C':
case 'G':
case 'J':
case 'K':
case 'Q':
case 'S':
case 'X':
case 'Z':
return '2';
case 'D':
case 'T':
return '3';
case 'M':
case 'N':
return '5';
case 'R':
return '6';
default:
return '.';
}
}
std::size_t SoundexHash(const std::string& word)
{
std::string soundex;
soundex.reserve(word.length());
BOOST_FOREACH(char ch, word)
{
if (std::isalpha(ch))
{
ch = std::toupper(ch);
if (soundex.length() == 0)
{
soundex.append(1, ch);
}
else
{
ch = SoundexChar(ch);
if (soundex.at(soundex.length() - 1) != ch)
{
soundex.append(1, ch);
}
}
}
}
soundex.erase(std::remove(soundex.begin(), soundex.end(), '.'), soundex.end());
if (soundex.length() < 4)
{
soundex.append(4 - soundex.length(), '0');
}
else if (soundex.length() > 4)
{
soundex = soundex.substr(0, 4);
}
return boost::hash_value(soundex);
}
int main()
{
std::cout << "Color = " << SoundexHash("Color") << std::endl;
std::cout << "Colour = " << SoundexHash("Colour") << std::endl;
std::cout << "Gray = " << SoundexHash("Gray") << std::endl;
std::cout << "Grey = " << SoundexHash("Grey") << std::endl;
return 0;
}