
【大数据头歌实验八】大数据综合实验(旅游网站大数据分析 - 数据清洗)
【代码】【大数据头歌实验八】大数据综合实验(旅游网站大数据分析 - 数据清洗)
·
第1关:清洗HTML文档中无意义数据
package step1;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
public class Task {
//通过filePath文件路径获取Docment对象
public Document getDoc(String filePath) throws IOException{
/********** Begin **********/
File input = new File(filePath);
Document doc = Jsoup.parse(input,"UTF-8","http://www.educoder.net/");
return doc;
/********** End **********/
}
/**
* 获取清理后的信息
* @param doc
* @return
*/
public List<String> cleanHTML(Document doc){
/********** Begin **********/
List<String> list=new ArrayList<>();
list.add(Jsoup.clean(doc.toString(), Whitelist.basic()));
list.add(Jsoup.clean(doc.toString(), Whitelist.simpleText()));
return list;
/********** End **********/
}
}
第2关:获取携程网北京市的所有酒店信息
package step2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
public class Task {
/**
* 使用fastjson解析数据
* @param hotelResult 已经为你解析的所需json数据
* @return
*/
public List<Hotel> getHotle(String hotelResult){
/********** Begin **********/
List<Hotel> hotels = new ArrayList<Hotel>();
// 解析酒店数据
JSONObject hotelResultObj = JSONObject.parseObject(hotelResult);
List<Hotel> pageHotels = JSON.parseArray(hotelResultObj.getString("hotelPositionJSON"), Hotel.class);
// 增加价格数据
JSONArray hotelsPrice = hotelResultObj.getJSONArray("htllist");
if (hotelsPrice != null && !hotelsPrice.isEmpty()) {
for (int j = 0; j < pageHotels.size(); j++) {
JSONObject priceObj = hotelsPrice.getJSONObject(j);
if (priceObj != null && !priceObj.isEmpty()) {
Hotel hotel = pageHotels.get(j);
String hotelId = priceObj.getString("hotelid");
double price = priceObj.getDoubleValue("amount");
if (hotel.getId().equals(hotelId)) {
hotel.setPrice(price);
}
}
}
}
hotels.addAll(pageHotels);
return hotels;
/********** End **********/
}
/**
* 由于携程网站经常更新,为了不影响测试,我们直接读取本地文件。
* @return
*/
public String getHotelListString(String cityId,String url){
String hotelResult="";
try {
InputStream is = new FileInputStream(new File("src/step2/hotelResult.txt"));
byte[] b=new byte[1024];
int len=0;
try {
while((len=is.read(b))!=-1){
String str=new String(b,0,len);
hotelResult+=str;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return hotelResult;
}
}
更多推荐
所有评论(0)