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>
用听错的“哈罗”表达了自己的想法。Alexander Graham Bell 最初使用 Ahoy(在船上使用)作为电话问候语`
colorHighlight(text, keywords); // will produce:
托马斯·爱迪生曾将其
<b style='background-color:#ffff66'>hello</b>
用作电话问候语;>据一位消息人士称,他用<b style='background-color:#a0ffff'>surprise</b>
听错的哈洛语表达了他的意思。Alexander Graham Bell 最初使用 Ahoy(在船上使用)作为电话问候语
问题:
有什么我可以使用的东西,比如第三方库,它可以像下面的方法一样做类似的工作吗?或者,如果您查看代码,是否有可以改进的地方,以提高性能和/或使其更优雅?
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()
请参阅我的另一篇文章:Removing strings from another string in java