boldHighlight メソッドはテキスト文字列を受け取り、その中の q キーワードを<b></b>
タグで強調表示します
colorHighlight メソッドはテキスト文字列を受け取り<b style='background-color: #color'></b>
、12 色を交互に使用してint q キーワードを強調表示します
String text = "The use of hello as a telephone greeting has been credited to Thomas
Edison; according to one source, he expressed his surprise with a
misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on
ships) as a telephone greeting"
String keywords = "HELLO Surprise"
boldHighlight(text, keywords); // will produce:
を電話のあいさつとして使用し
<b>hello</b>
たのは、Thomas Edison の功績によるものです。<b>surprise</b>
ある情報筋によると、彼は聞き間違いのハロで彼を表現しました。アレクサンダー・グラハム・ベルは当初、電話のあいさつとしてアホイ(船で使用されていたもの)を使用しました。
colorHighlight(text, keywords); // will produce:
を電話のあいさつとして使用し
<b style='background-color:#ffff66'>hello</b>
たのは、トーマス エジソンの功績によるものです。ある情報源によると、彼は<b style='background-color:#a0ffff'>surprise</b>
聞き間違いのハロで表現しました。アレクサンダー グラハム ベルは当初、アホイ (船で使用されていたもの) を電話のあいさつとして使用していました。
質問:
以下の方法と同様の仕事をするサードパーティのライブラリのように使用できるものはありますか? または、コードを見て、パフォーマンスを向上させたり、よりエレガントにしたりするために、改善できるものはありますか?
private static final String[] colors = new String[]{"ffff66", "a0ffff", "99ff99", "ff9999", "ff66ff", "880000", "00aa00", "886800", "004699", "990099", "ffff66", "a0ffff"};
public static String safeCharWithSpace(String input) {
input = input.trim();
return Normalizer.normalize(input.toLowerCase(), Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.replaceAll("[^\\p{Alnum}]+", " ");
}
private static String prepQuery(String q) {
try {
log.debug("qr encoded: " + q);
q = URLDecoder.decode(q, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
log.debug("qr decoded: " + q);
return removeIgnoreCase(q, stopWords);
}
public static String boldHighlight(String text, String q) {
return highlight(text, q, false);
}
public static String colorHighlight(String text, String q) {
return highlight(text, q, true);
}
private static String replaceWord(String text, String keyword, int colorNumber, boolean useColor) {
String color = "";
keyword = safeCharWithSpace(keyword);
if (StringUtils.isNotEmpty(keyword) && !StringUtils.isWhitespace(keyword)) {
if (useColor) color = " style='background-color: " + colors[colorNumber] + "'";
return text.replaceAll("(?i)(" + keyword + ")(?!([^<]+)?>>)", "<b" + color + ">$1</b>");
} else
return text;
}
public static String highlight(String text, String q, boolean useColor) {
String qr = prepQuery(q);
String rtn = null;
int i = 0;
if (qr.startsWith("\"")) {
String keywords = StringUtils.remove(qr, "\"");
rtn = replaceWord(text, keywords, 0, useColor);
} else {
String[] keywords = qr.split("\\s");
for (String keyword : keywords) {
rtn = replaceWord(text, keyword, i, useColor);
if (useColor) {
if (i < 11) i++;
else i = 0;
}
}
}
return rtn;
}
removeIgnoreCase()
メソッド内のストップ ワードの削除prepQuery()
については、私の他の投稿を参照してください: Java で別の文字列から文字列を削除する