Apache Commons LevenshteinDistance莱文斯坦(相似度)算法
admin
2024-01-27 22:58:33
0次

Apache Commons LevenshteinDistanceLevenshteinDistance(final Integer threshold) 如果阈值不为空,则距离计算将限制为最大长度。

介绍

如果阈值不为空,则距离计算将受到限制 到最大长度。

如果阈值为 null,则算法的无限版本将 被使用。

LevenshteinDistance() 方法是一个构造函数。

语法

来自LevenshteinDistance 的方法 LevenshteinDistance() 声明为:

复制

public LevenshteinDistance(final Integer threshold)

参数

LevenshteinDistance() 方法具有以下参数:

  • 整数阈值 - 如果此值为空,则距离计算将不受限制。这可能不是负面的。

例

以下代码演示如何使用 Apache CommonsLevenshteinDistance LevenshteinDistance(final Integer threshold)

例 1

复制

import org.apache.commons.text.*;
import org.apache.commons.text.diff.*;
import org.apache.commons.text.similarity.*;
import org.apache.commons.text.translate.*;import java.util.HashMap;
import java.util.Locale;
import java.util.Map;class ShowVisitor<Character> implements CommandVisitor<Character> {private int inserts = 0;private int keeps = 0;private int deletes = 0;public void visitInsertCommand(Character character) {++inserts;//   w w   w  .  d e  m  o   2 s    .  c o  m System.out.println(String.format("insert %s", character));}public void visitKeepCommand(Character character) {++keeps;System.out.println(String.format("keep   %s", character));}public void visitDeleteCommand(Character character) {++deletes;System.out.println(String.format("delete %s", character));}public void printStats() {System.out.println(String.format("%d inserts, %d deletes, %d keeps", inserts, deletes, keeps));}
}public class CommonsTextExamples {public static void main(String[] args) {caseUtilsExample();stringEscapeUtilsExample();stringSubstitutorExample();wordUtilsExample();diffExample();translateExample();similaritiesExample();sentenceSimilarityExample();distancesExample();sentenceDistanceExample();}private static void printExampleHeader(String example) {// Contains an example of TextStringBuilderString header = "Examples of " + example;System.out.println("\n" + header);TextStringBuilder builder = new TextStringBuilder();System.out.println(builder.appendPadding(header.length(), '-').toString());}public static void caseUtilsExample() {printExampleHeader("CaseUtils");String string = "java-programming-language";System.out.println(CaseUtils.toCamelCase(string, true, '-'));System.out.println(CaseUtils.toCamelCase(string, false, '-'));}public static void stringEscapeUtilsExample() {printExampleHeader("StringEscapeUtils");String string = "Department, R&D";System.out.println(StringEscapeUtils.escapeHtml4(string));System.out.println(StringEscapeUtils.escapeXml11(string));System.out.println(StringEscapeUtils.escapeCsv(string));System.out.println(StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4).append("R&D dept: ").escape(string).toString());}public static void stringSubstitutorExample() {printExampleHeader("StringSubstitutor");Map<String, String> substitutions = new HashMap<>();substitutions.put("city", "London");substitutions.put("country", "England");// With static methodSystem.out.println(StringSubstitutor.replace("${city} is the capital of ${country}", substitutions));// With StringSubstitutor objectStringSubstitutor sub = new StringSubstitutor(substitutions);System.out.println(sub.replace("${city} is the capital of ${country}"));StringSubstitutor interpolator = StringSubstitutor.createInterpolator();System.out.println(interpolator.replace("Base64 encoder: ${base64Encoder:Secret password}"));}public static void wordUtilsExample() {printExampleHeader("WordUtils");String longString = "This is a very long string, from https://www.example.org";String allLower = "all lower but ONE";String allCapitalized = "All Capitalized But ONE";System.out.println("\nWordUtils: Abbreviation");// Take at least 9 characters, cutting to 12 characters if no space is found beforeSystem.out.println(WordUtils.abbreviate(longString, 9, 12, " ..."));// Take at least 10 characters, cutting to 12 characters if no space is found beforeSystem.out.println(WordUtils.abbreviate(longString, 10, 12, " ..."));// Take at least 10 characters, then cut on the first space wherever it isSystem.out.println(WordUtils.abbreviate(longString, 10, -1, " ..."));System.out.println("\nWordUtils: Initials");System.out.println(WordUtils.initials(allLower));System.out.println(WordUtils.initials(allCapitalized));System.out.println("\nWordUtils: Case change");// Doesn't lowercase the uppercase charactersSystem.out.println(WordUtils.capitalize(allLower));// Lowercases everything, then capitalizes the first letter of each wordSystem.out.println(WordUtils.capitalizeFully(allLower));// Lowercases the first letter of each wordSystem.out.println(WordUtils.uncapitalize(allCapitalized));// Swaps the case of each characterSystem.out.println(WordUtils.swapCase(allLower));System.out.println("\nWordUtils: Wrapping");// Line length is 10, uses '\n' as a line break, does not break words longer than the lineSystem.out.println(WordUtils.wrap(longString, 10, "\n", false) + "\n");// Line length is 10, uses '\n' as a line break, breaks words longer than the lineSystem.out.println(WordUtils.wrap(longString, 10, "\n", true) + "\n");// Line length is 10, uses '\n' as a line break, breaks words longer than the line, also breaks on commasSystem.out.println(WordUtils.wrap(longString, 10, "\n", true, ",") + "\n");}public static void diffExample() {printExampleHeader("diff");String s1 = "hyperspace";String s2 = "cyberscape";StringsComparator comparator = new StringsComparator(s1, s2);EditScript<Character> script = comparator.getScript();System.out.println("Longest Common Subsequence length (number of \"keep\" commands): " + script.getLCSLength());System.out.println("Effective modifications (number of \"insert\" and \"delete\" commands): "+ script.getModifications());ShowVisitor<Character> visitor = new ShowVisitor<>();script.visit(visitor);visitor.printStats();}public static void translateExample() {printExampleHeader("translate");Map<CharSequence, CharSequence> translation = new HashMap<>();translation.put("e", "3");translation.put("l", "1");translation.put("t", "7");String s1 = "Let it be!";LookupTranslator lookupTranslator = new LookupTranslator(translation);System.out.println(lookupTranslator.translate(s1));UnicodeEscaper unicodeEscaper = new UnicodeEscaper();UnicodeUnescaper unicodeUnescaper = new UnicodeUnescaper();String unicodeString = unicodeEscaper.translate(s1);System.out.println(unicodeString);System.out.println(unicodeUnescaper.translate(unicodeString));}public static void similaritiesExample() {printExampleHeader("similarities");String s1 = "hyperspace";String s2 = "cyberscape";JaccardSimilarity jaccard = new JaccardSimilarity();System.out.println("Jaccard similarity: " + jaccard.apply(s1, s2));JaroWinklerSimilarity jaroWinkler = new JaroWinklerSimilarity();System.out.println("Jaro-Winkler similarity: " + jaroWinkler.apply(s1, s2));LongestCommonSubsequence lcs = new LongestCommonSubsequence();System.out.println("Longest Common Subsequence similarity: " + lcs.apply(s1, s2));FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);System.out.println("Fuzzy score similarity: " + fuzzyScore.fuzzyScore(s1, s2));System.out.println("Fuzzy score similarity: " + fuzzyScore.fuzzyScore(s1, "space"));}public static void sentenceSimilarityExample() {printExampleHeader("sentence similarity");String s1 = "string similarity";String s2 = "string distance";Map<CharSequence, Integer> vector1 = new HashMap<>();Map<CharSequence, Integer> vector2 = new HashMap<>();for (String token : s1.split(" ")) {vector1.put(token, vector1.getOrDefault(token, 0) + 1);}for (String token : s2.split(" ")) {vector2.put(token, vector2.getOrDefault(token, 0) + 1);}CosineSimilarity cosine = new CosineSimilarity();System.out.println("Cosine similarity: " + cosine.cosineSimilarity(vector1, vector2));// Adding one repetition of "string" to vector2vector2.put("string", vector2.getOrDefault("string", 0) + 1);System.out.println("Cosine similarity: " + cosine.cosineSimilarity(vector1, vector2));}public static void distancesExample() {printExampleHeader("distances");String s1 = "hyperspace";String s2 = "cyberscape";HammingDistance hamming = new HammingDistance();// Requires the two strings to have the same lengthSystem.out.println("Hamming distance: " + hamming.apply(s1, s2));JaccardDistance jaccard = new JaccardDistance();System.out.println("Jaccard distance: " + jaccard.apply(s1, s2));JaroWinklerDistance jaroWinkler = new JaroWinklerDistance();// The result is wrong at the moment (see https://issues.apache.org/jira/browse/TEXT-104)System.out.println("Jaro-Winkler distance: " + jaroWinkler.apply(s1, s2));LongestCommonSubsequenceDistance lcs = new LongestCommonSubsequenceDistance();System.out.println("Longest Common Subsequence distance: " + lcs.apply(s1, s2));LevenshteinDistance levenshtein = new LevenshteinDistance();System.out.println("Levenshtein distance: " + levenshtein.apply(s1, s2));LevenshteinDistance levenshteinWithThreshold = new LevenshteinDistance(3);// Returns -1 since the actual distance, 4, is higher than the thresholdSystem.out.println("Levenshtein distance: " + levenshteinWithThreshold.apply(s1, s2));LevenshteinDetailedDistance levenshteinDetailed = new LevenshteinDetailedDistance();System.out.println("Levenshtein detailed distance: " + levenshteinDetailed.apply(s1, s2));}public static void sentenceDistanceExample() {printExampleHeader("sentence distance");String s1 = "string similarity";String s2 = "string distance";CosineDistance cosine = new CosineDistance();System.out.println("Cosine distance: " + cosine.apply(s1, s2));System.out.println("Cosine distance: " + cosine.apply(s1, s2 + " string"));}
}

相关内容

热门资讯

蜻蜓订购APP贵金属订购非法期...   蜻蜓订购APP以"投资平台"名义对外宣传,主打贵金属期货(订购)交易。该平台一方面强调自身"正规...
悟空订购APP非法期货交易欺骗...   近期,有投资者反映,“悟空订购APP”等平台以白银、贵金属订购为名,宣传所谓“高收益”“低门槛”...
小赢淘金APP期货投资骗局,平...   “小赢淘金”之流,最擅长的就是用“注册送现金”、“充值返券”的糖衣炮弹来引流。别天真地以为那是福...
八方淘金APP非法期货交易欺骗...   警惕!八方生财、每日淘金、小赢淘金、悟空订购、蜻蜓订购、斗金订购等APP均涉嫌非法期货交易!  ...
智易购APP贵金属订购交易骗局...   很多人看到“3元起投”“充值送福利”“操作简单”“随时提现”这类宣传,很容易把智易购APP当成普...
喜玛银庄APP商品订购投资骗局...   喜玛银庄APP白银、铂金“现货订购”骗局警示:无资质平台涉嫌非法期货交易,投资者爆仓后如何维权?...
吉鑫乐享APP炒贵金属订购交易...   近期,多名投资者反映在“吉鑫乐享APP”进行贵金属投资时遭遇严重亏损,甚至血本无归。看似正规的“...
易掘金APP虚假期货投资骗局,...   “易掘金”的APP它打着“高收益、灵活投资”的旗号,宣称通过“商品订购”就能轻松赚钱,吸引了不少...
在大吉订购APP订购交易亏损被...   近期,不少投资者反映在“大吉订购App”上投资白银、铂金等商品遭遇严重亏损。该平台宣称提供现货订...
铂银壹号APP商品订购交易亏损...   许多中小投资者误以为网上的“商品现货订购”是合规合法的理财渠道,殊不知这背后隐藏着巨大的合规风险...
兴鑫淘金APP贵金属订购交易亏...   白银、贵金属或其他商品类投资,除国家批准的正规期货交易场所及持牌期货公司外,市面上大量第三方交易...
铂银掘金APP无资质的违规平台...   铂银掘金等平台的投资者,往往是被“注册送现金”“充值返现券”“首单免亏”等广告话术吸引,进而下载...
八方淘金APP订购交易不合规,...   “八方淘金APP”“铂银掘金APP”“铂银壹号APP”等软件被指以“现货订购”为名,实际采用高杠...
在指尖订购APP订购商品亏损被...   指尖订购APP这类平台,表面是“订购交易”,实则是披着电商外衣的非法期货陷阱。绝大多数投资者被蒙...
在犀贝易购APP做商品订购交易...   市面上打着“现货投资”“贵金属交易”旗号的APP并不少,但真正合规、受监管的平台并不多。犀贝易购...
易达淘金APP虚假商品订购交易...   易达淘金APP存在严重的虚假宣传与违规交易行为。该平台打着“商品订购”的旗号,实则通过不合规的交...
大浪淘金APP白银订购亏损被骗...   大浪淘金APP最隐蔽的套路,在于其完全封闭的内盘交易系统。表面上,它宣称与国际贵金属市场接轨;实...
一品好购APP上订购白银出现亏...   一品好购APP原名“一品订购”,运营方为上海宝智未来信息技术有限公司。近期不少投资者反映在该平台...
九州订购APP贵金属订购投资骗...   九州订购APP正通过抖.音、快手、今日头条等平台大量投放投资广告,用“5元起投”“充值返现”“0...
坚锅淘金APP交易软件并不正规...   当前,市面上大量所谓的“现货商城订购”交易软件,早已偏离了正常的实物商品买卖,演变为高杠杆、高手...