離上次更新文章已經(jīng)將近半年的時(shí)間了,該穩(wěn)定的基本穩(wěn)定了:),以后要保持更新文章的頻率,不能荒廢。話不多說,進(jìn)入正題。
最近做的一個(gè)項(xiàng)目需要把爬蟲抓取的數(shù)據(jù)進(jìn)行清洗,自己第一次做相關(guān)的東西,有什么不對(duì)的地方,還望多多指正。
1、拿到的原始數(shù)據(jù)

Json格式的數(shù)據(jù),但漢字都是Unicode編碼,還有Html的標(biāo)簽比如<span>,還有轉(zhuǎn)義字符,其實(shí)還包括一些特定的東西,這個(gè)就根據(jù)實(shí)際情況來了,比如這個(gè)就包括了“收起”的Unicode編碼(左下角的\u6536\u8d77)
2、處理過程
字符串比較多,直接貼圖

1)第一步過濾Html標(biāo)簽
<code>
str = HtmlRegexpUtil.filterHtml(str);
</code>
前后對(duì)比

貼一下HtmlRegexpUtil的代碼(非原創(chuàng))
<code>
private final static String regxpForHtml = "<([^>]*)>"; // 過濾所有以<開頭以>結(jié)尾的標(biāo)簽
public static String filterHtml(String str) {
Pattern pattern = Pattern.compile(regxpForHtml);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
boolean result1 = matcher.find();
while (result1) {
matcher.appendReplacement(sb, "");
result1 = matcher.find();
}
matcher.appendTail(sb);
return sb.toString();
}
</code>
2)把Unicode轉(zhuǎn)成字符串

結(jié)果

顯示可以成功轉(zhuǎn)義,但里面還有一些其他的字符,直接在.trim()后面加上.replace("\t","")即可

TestVo一個(gè)普通的Bean而已,和Json數(shù)據(jù)是相對(duì)應(yīng)的,簡(jiǎn)單的貼一下

主要是EncodingUtil.unicodeToString,這個(gè)從網(wǎng)上找了好幾個(gè),貼一個(gè)最合適的,其他的多多少少會(huì)有問題。
<code>
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\u(\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
</code>
對(duì)這邊有點(diǎn)不是很熟悉,寫的有點(diǎn)凌亂,大家多多包涵~