gpt4 book ai didi

java - Metaphone 算法的意外结果

转载 作者:行者123 更新时间:2023-11-30 03:39:28 25 4
gpt4 key购买 nike

我在 Java 中对不同单词使用语音匹配。我用过 Soundex,但它太粗糙了。我改用 Metaphone 并意识到它更好。然而,当我严格测试它时。我发现奇怪的行为。我想问这是否是变音位的工作方式,或者我是否以错误的方式使用它。在下面的例子中它工作正常:-

Metaphone meta = new Metaphone();
if (meta.isMetaphoneEqual("cricket","criket")) System.out.prinlnt("Match 1");
if (meta.isMetaphoneEqual("cricket","criketgame")) System.out.prinlnt("Match 2");

这将打印

  Match 1
Mathc 2

现在“cricket”听起来确实像“cricket”,但为什么“cricket”和“cricketgame”是相同的。如果有人能解释一下这一点。这会有很大的帮助。

最佳答案

您的用法有点不正确。对编码字符串和默认最大代码长度的快速调查表明它是 4,它截断了较长“cricketgame”的末尾:

System.out.println(meta.getMaxCodeLen());
System.out.println(meta.encode("cricket"));
System.out.println(meta.encode("criket"));
System.out.println(meta.encode("criketgame"));

输出(注意“cricketgame”从“KRKTKM”被截断为“KRKT”,与“cricket”匹配):

4KRKTKRKTKRKT


Solution: Set the maximum code length to something appropriate for your application and the expected input. For example:

meta.setMaxCodeLen(8);
System.out.println(meta.encode("cricket"));
System.out.println(meta.encode("criket"));
System.out.println(meta.encode("criketgame"));

现在输出:

KRKTKRKTKRKTKM

And now your original test gives the expected results:

Metaphone meta = new Metaphone();
meta.setMaxCodeLen(8);
System.out.println(meta.isMetaphoneEqual("cricket","criket"));
System.out.println(meta.isMetaphoneEqual("cricket","criketgame"));

打印:

truefalse

顺便说一句,您可能还想尝试 DoubleMetaphone ,这是该算法的改进版本。

<小时/>

顺便说一句,请注意 the documentation 中的警告关于线程安全:

The instance field maxCodeLen is mutable but is not volatile, and accesses are not synchronized. If an instance of the class is shared between threads, the caller needs to ensure that suitable synchronization is used to ensure safe publication of the value between threads, and must not invoke setMaxCodeLen(int) after initial setup.

关于java - Metaphone 算法的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093831/

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