修改代码字符编码

This commit is contained in:
2026-02-24 17:53:50 +08:00
parent 2495fe5f6d
commit c8418c7d4b
5195 changed files with 121754 additions and 121754 deletions
@@ -70,14 +70,14 @@ public class ModeAnalyze {
}
/**
* 模式解析
* 模式解析
*
* @param text
* 输入文本
* 输入文本
* @param cat
* 所属类型
* 所属类型
* @param fields
* 要解析的字段列表
* 要解析的字段列表
* @return
*/
public static Map<String, Object> analyze(String text, String cat, List<String> fields) {
@@ -91,12 +91,12 @@ public class ModeAnalyze {
}
}
// 输入文本为空
// 输入文本为空
if (StringUtils.isBlank(text)) {
return Collections.emptyMap();
}
// 获得所属类型的解析配置
// 获得所属类型的解析配置
List<ModeAnalyField> tmpFields;
if (StringUtils.isBlank(cat)) {
tmpFields = FIELDS.get("all");
@@ -108,7 +108,7 @@ public class ModeAnalyze {
return Collections.emptyMap();
}
// 获取要用的解析配置
// 获取要用的解析配置
List<ModeAnalyField> anaFields = new ArrayList<ModeAnalyField>();
if (CollectionUtils.isNotEmpty(fields)) {
for (ModeAnalyField f : tmpFields) {
@@ -124,7 +124,7 @@ public class ModeAnalyze {
return Collections.emptyMap();
}
// 开始解析
// 开始解析
Map<String, Object> ret = new HashMap<String, Object>(anaFields.size());
String[] strArr = text.split("\n");
for (int i = 0; i < strArr.length; i++) {
@@ -165,7 +165,7 @@ public class ModeAnalyze {
if (null == str)
return null;
str = str.replaceAll("^[\\s ]*|[\\s ]*$", "");
str = str.replaceAll("^[\\s ]*|[\\s ]*$", "");
str = str.replaceAll("&nbsp;", "");
str = DataUtil.encoding(str).replaceAll("^\\?*|\\?*$", "");
return str;
@@ -201,7 +201,7 @@ public class ModeAnalyze {
public static void main(String[] args) {
/*Map<String, Object> ret = analyze(
"装修状况:暂无 预售证:暂无 产权年限:暂无 物业费:0.50元/平 建筑面积:22000平方米 绿化率:37.3% 物业公司:暂无 容积率:0.86 交通状况:主要公交路线8路、2路 停车位:暂无 ", null,
"装修状况:暂无 预售证:暂无 产权年限:暂无 物业费:0.50元/平 建筑面积:22000平方米 绿化率:37.3% 物业公司:暂无 容积率:0.86 交通状况:主要公交路线8路、2路 停车位:暂无 ", null,
null);
for (String k : ret.keySet()) {
System.out.println(k + " : " + ret.get(k));
@@ -2,7 +2,7 @@ package com.fangjia.coredata.price;
/**
* ºǫ́¼ÆËãÐ¡Çø¾ù¼Û
* 后台计算小区均价
*
* @author xiaoyu
*
@@ -55,7 +55,7 @@ public class ConsumerStarter {
// removeDistrictStat(weekends.get(0), command.getCity(), command.getRegion(), command.getDistrictName());
// for (Date weekend : weekends) {
// Coredata coredata = new Coredata(CalcDataCategoryEnum.SELL, command.getCity(), weekend, SAMPLE_DAY);
// if (commandDistrict.isVilla() && "±ðÊû".equals(command.getEstateType())) {
// if (commandDistrict.isVilla() && "别墅".equals(command.getEstateType())) {
// coredata.calcDistrict(command.getRegion(), command.getDistrictName(), CategoryEnum.DISTRICT,
// EstateTypeEnum.VILLA);
// isrecalc = true;
@@ -97,33 +97,33 @@ public class Coredata {
dataHolder = new DataHolder(dataCategory, city, calcDate, sampleDay,enable_memory);
if (CalcDataCategoryEnum.SELL.equals(dataCategory)) {// 二手房均价
if (CalcDataCategoryEnum.SELL.equals(dataCategory)) {// 二手房均价
provider = new SellHouseDataProvider(dataHolder);
calculator = new SellHouseAverageCalculator(provider);
operator = new SellHouseResultOperator();
categoryEnum = CategoryEnum.DISTRICT;
} else if (CalcDataCategoryEnum.SHOP_SELL.equals(dataCategory)) {// 商铺出售均价
} else if (CalcDataCategoryEnum.SHOP_SELL.equals(dataCategory)) {// 商铺出售均价
provider = new SellShopOfficeDataProvider(dataHolder);
calculator = new SellShopOfficeAverageCalculator(provider);
operator = new SellShopOfficeResultOperator();
categoryEnum = CategoryEnum.SHOP;
} else if (CalcDataCategoryEnum.OFFICE_SELL.equals(dataCategory)) {// 写字楼出售均价
} else if (CalcDataCategoryEnum.OFFICE_SELL.equals(dataCategory)) {// 写字楼出售均价
provider = new SellShopOfficeDataProvider(dataHolder);
calculator = new SellShopOfficeAverageCalculator(provider);
operator = new SellShopOfficeResultOperator();
categoryEnum = CategoryEnum.OFFICE;
} else if (CalcDataCategoryEnum.SHOP_RENT.equals(dataCategory)) {// 商铺出租均价
} else if (CalcDataCategoryEnum.SHOP_RENT.equals(dataCategory)) {// 商铺出租均价
provider = new RentShopOfficeDataProvider(dataHolder);
calculator = new RentShopOfficeAverageCalculator(provider);
operator = new RentShopOfficeResultOperator();
categoryEnum = CategoryEnum.SHOP;
}else if (CalcDataCategoryEnum.OFFICE_RENT.equals(dataCategory)) {// 写字楼出租均价
}else if (CalcDataCategoryEnum.OFFICE_RENT.equals(dataCategory)) {// 写字楼出租均价
provider = new RentShopOfficeDataProvider(dataHolder);
calculator = new RentShopOfficeAverageCalculator(provider);
operator = new RentShopOfficeResultOperator();
categoryEnum = CategoryEnum.OFFICE;
}else if (CalcDataCategoryEnum.RENT.equals(dataCategory)) {// 小区租金均价
}else if (CalcDataCategoryEnum.RENT.equals(dataCategory)) {// 小区租金均价
provider = new RentHouseDataProvider(dataHolder);
calculator = new RentHouseAverageCalculator(provider);
operator = new RentHouseResultOperator();
@@ -132,7 +132,7 @@ public class Coredata {
}
/**
* 计算城市均价
* 计算城市均价
*
*/
public void calcCity() {
@@ -141,7 +141,7 @@ public class Coredata {
}
/**
* 计算城市的区域均价
* 计算城市的区域均价
*
*/
public void calcRegion() {
@@ -155,7 +155,7 @@ public class Coredata {
}
/**
* 计算城市的板块均价
* 计算城市的板块均价
*
*/
public void calcBlock() {
@@ -174,7 +174,7 @@ public class Coredata {
}
/**
* 计算城市的小区均价
* 计算城市的小区均价
*
*/
public void calcDistrict() {
@@ -183,7 +183,7 @@ public class Coredata {
int c = 0;
for (DistrictKey key : districtMap.keySet()) {
if(c == 2584){
System.out.println("怡德苑-闵行-上海");
System.out.println("怡德苑-闵行-上海");
}
LOGGER.info("calc district " + (++c) + "/" + districtMap.size() + " " + key.getName() + "-" + key.getRegion() + "-"
+ key.getCity());
@@ -228,7 +228,7 @@ public class Coredata {
/**
* 计算城市的小区租金
* 计算城市的小区租金
*
*/
public void calcDistrictRent() {
@@ -273,16 +273,16 @@ public class Coredata {
Date startDate = DateUtil.truncateDay(DateUtil.add(calcDate, 365*(-1))) ;
Date endDate = DateUtil.truncateDay(DateUtil.getLastDayOfMonth(DateUtil.add(DateUtil.add(calcDate, sampleDay*(-1)), -5)));
//区域涨跌幅
//区域涨跌幅
final Map<String, Map<Integer, Map<String, Integer>>> regionMarkupMap = regionStatRentDao.findRegionMarkup(city, startDate, endDate);
System.out.println(regionMarkupMap.size());
//小区数据
//小区数据
Map<DistrictKey, District> districtMap = districtDao.getDistrictByCity(city, categoryEnum);
System.out.println("小区Map数量: "+districtMap.size());
//房型数据
System.out.println("小区Map数量: "+districtMap.size());
//房型数据
final Map<String, List<Integer>> houseTypeMap = DistrictHouseTypeDao.getInstance().findDistrictHouseTypes(city);
System.out.println("房型Map数量: "+houseTypeMap.size());
//城市房型间跨度比
System.out.println("房型Map数量: "+houseTypeMap.size());
//城市房型间跨度比
final Map<Integer, Double> ratioMap = districtStatRentDao.findCityRoomSpanRatio(city, DateUtil.truncateDay(DateUtil.getLastDayOfMonth(calcDate, -1)));
@@ -297,7 +297,7 @@ public class Coredata {
continue;
}
// String[] names = {"成功家园"};
// String[] names = {"成功家园"};
// if(StringUtils.indexOfAny(district.getName(), names)==-1){
// continue;
// }
@@ -307,8 +307,8 @@ public class Coredata {
public void run() {
String estateType = district.getEstateType2();
if(StringUtils.isNotBlank(estateType) && !estateType.equals("别墅")){
estateType = "小区";
if(StringUtils.isNotBlank(estateType) && !estateType.equals("别墅")){
estateType = "小区";
}
String key = district.getRegion()+"@"+district.getName()+"@"+estateType;
List<Integer> roomList = houseTypeMap.get(key);
@@ -349,7 +349,7 @@ public class Coredata {
}
/**
* 计算小区租金覆盖率
* 计算小区租金覆盖率
*/
public void calcDistrictCover(){
LOGGER.info("calc district rent cover of " + city);
@@ -386,7 +386,7 @@ public class Coredata {
/**
* 小区计算
* 小区计算
*
* @param districtKey
* @param calcDate
@@ -491,7 +491,7 @@ public class Coredata {
/**
* 从租房房源中提取房型
* 从租房房源中提取房型
*/
public void calcDistrictHouseType(Map<DistrictKey, District> districtMap){
@@ -506,14 +506,14 @@ public class Coredata {
if(datas.size() > 0){
List<Integer> rooms = new ArrayList<Integer>();
for (Data d : datas) {
if(estateType.equals("小区") && !d.isVilla() && !d.isVilla() && d.getRoom()>5){
if(estateType.equals("小区") && !d.isVilla() && !d.isVilla() && d.getRoom()>5){
continue;
}
if(!rooms.contains(d.getRoom())){
if(estateType.equals("别墅") && d.isVilla()){
if(estateType.equals("别墅") && d.isVilla()){
rooms.add(d.getRoom());
}else if(estateType.equals("小区") && !d.isVilla()){
}else if(estateType.equals("小区") && !d.isVilla()){
rooms.add(d.getRoom());
}
@@ -546,7 +546,7 @@ public class Coredata {
/**
* 计算城市的区域租金
* 计算城市的区域租金
*
*/
public void calcRegionRent() {
@@ -572,7 +572,7 @@ public class Coredata {
/**
* 计算指定小区的均价
* 计算指定小区的均价
*
* @param region
* @param districtName
@@ -585,7 +585,7 @@ public class Coredata {
}
/**
* 小区计算
* 小区计算
*
* @param districtKey
* @param calcDate
@@ -647,7 +647,7 @@ public class Coredata {
}
/**
* 城市计算
* 城市计算
*
* @param cityKey
* @param calcDate
@@ -821,16 +821,16 @@ public class Coredata {
}
public void calcDistrictSqMetreRent(final int sampleDay) throws InterruptedException{
//查询区域平米均价涨跌幅
//查询区域平米均价涨跌幅
Date date = DateUtil.add(calcDate, sampleDay*(-1));
Date startDate = DateUtil.truncateDay(DateUtil.getFirstDayOfLastMonth(DateUtil.add(calcDate, sampleDay*(-1)))) ;
final Map<String, Map<String, Double>> regionMarkupMap = getRegionSqMarkup(city, startDate, calcDate);
Map<DistrictKey, District> districtMap = districtDao.getDistrictByCity(city, categoryEnum);
System.out.println("小区共:"+districtMap.size());
//查询最后一次的城市均价
System.out.println("小区共:"+districtMap.size());
//查询最后一次的城市均价
final RegionStat cityRegion = regionStatDao.findLastRegionStat(city, null, null);
//查询最后一次的城市平米租金
//查询最后一次的城市平米租金
SqmetreRent cityRegionRent = sqmetreRegionRentDao.findNewestRegionSqmetreStat(city, null, null);
final Double rentRatio = getCityRentRatio(cityRegionRent, cityRegion);
@@ -839,7 +839,7 @@ public class Coredata {
final List<String> ret = Collections.synchronizedList(new ArrayList());
for(final DistrictKey districtKey : districtMap.keySet()){
// String[] names = {"永陵路36号院"};
// String[] names = {"永陵路36号院"};
// if(StringUtils.indexOfAny(districtKey.getName(), names)==-1){
// continue;
// }
@@ -15,7 +15,7 @@ import com.fangjia.mongo.dao.ServerAreaDao;
import com.fangjia.mongo.model.CalcCommand;
/**
* 小区租金计算
* 小区租金计算
* @author gaojuan
*
*/
@@ -48,13 +48,13 @@ public class RentHouseCoredata {
LOGGER.info("start month " + DateUtil.formatToTightYYYYMMDDhhmmss(command.getCalcDate()) + " of " + command.getCity());
calcCommandDao.updateToCalcing(command.getId());
Coredata coredata = new Coredata(CalcDataCategoryEnum.RENT, command.getCity(), command.getCalcDate(), SAMPLE_DAY, true, false);
coredata.calcDistrictRent();//计算小区租金
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
coredata.calcDistrictRent();//计算小区租金
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
index ++;
calcCommandDao.updateToSuc(command.getId());
LOGGER.info("-----------【"+index+"/"+commands.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
LOGGER.info("-----------【"+index+"/"+commands.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
}
}else{
LOGGER.info("end. invalid calc.start_date!!!");
@@ -71,7 +71,7 @@ public class RentHouseCoredata {
return;
}
List<String> citys = Arrays.asList("常州");//ServerAreaDao.getInstance().findAllCity();
List<String> citys = Arrays.asList("常州");//ServerAreaDao.getInstance().findAllCity();
LOGGER.info("calc total city " + citys.size());
int index = 0;
for(String city : citys){
@@ -85,10 +85,10 @@ public class RentHouseCoredata {
// continue;
// }
coredata.calcDistrictRent();//计算小区租金
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
coredata.calcDistrictRent();//计算小区租金
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
}
}
@@ -107,8 +107,8 @@ public class RentHouseCoredata {
// return;
// }
//List<String> citys = Arrays.asList("成都");
List<String> citys = ServerAreaDao.getInstance().findAllCity();//Arrays.asList("昆明");
//List<String> citys = Arrays.asList("成都");
List<String> citys = ServerAreaDao.getInstance().findAllCity();//Arrays.asList("昆明");
LOGGER.info("calc total city " + citys.size());
int index = 0;
int cityIndex = 0;
@@ -131,11 +131,11 @@ public class RentHouseCoredata {
LOGGER.info("start month " + DateUtil.formatToTightYYYYMMDDhhmmss(calDate) + " of " + city);
Coredata coredata = new Coredata(CalcDataCategoryEnum.RENT, city, calDate, SAMPLE_DAY, false, true);
coredata.calcDistrictRent2();//计算小区租金
coredata.calcDistrictRent2();//计算小区租金
coredata.calcCityRent();
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
coredata.calcRegionRent();//计算区域租金
coredata.calcDistrictCover();//小区租金覆盖率
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
}
}
@@ -19,7 +19,7 @@ import com.fangjia.mongo.dao.ServerAreaDao;
import com.fangjia.mongo.model.CalcCommand;
/**
* 商铺、写字楼租金计算
* 商铺、写字楼租金计算
*
*
*/
@@ -107,8 +107,8 @@ public class RentShopOfficeCoredata {
}
List<String> citys = ServerAreaDao.getInstance().findAllCity();
//List<String> citys = Arrays.asList("上海");
//String calcCity = "上海";
//List<String> citys = Arrays.asList("上海");
//String calcCity = "上海";
if (citys==null) {
LOGGER.info("end. invalid calc.city!!!");
return;
@@ -129,7 +129,7 @@ public class RentShopOfficeCoredata {
LOGGER.info("-----------------------------------------------------------------------------------");
for (String city : citys) {
if(city.equals("全国")){
if(city.equals("全国")){
continue;
}
@@ -27,7 +27,7 @@ public class RetryDistrictRentOperator {
for(CalcCommand command : commands){
Coredata coredata = new Coredata(CalcDataCategoryEnum.RENT, command.getCity(), command.getCalcDate(), 30, false, false);
calcCommandDao.updateToCalcing(command.getId());
coredata.calcRetryDistrictRent(command);//¼ÆËãÐ¡Çø×â½ð
coredata.calcRetryDistrictRent(command);//计算小区租金
calcCommandDao.updateToCalcSuc(command.getId());
}
@@ -18,7 +18,7 @@ import com.fangjia.coredata.price.conf.CoredataConfig;
import com.fangjia.mongo.dao.ServerAreaDao;
/**
* 二手房城市、小区均价计算
* 二手房城市、小区均价计算
*
* @author xiaoyu
*
@@ -100,14 +100,14 @@ public class SellHouseCoredata {
}
private List<String> getAllCities() {
return Arrays.asList(new String[] { "上海", "北京", "广州", "深圳", "天津", "重庆", "成都", "西安", "杭州", "武汉", "南京", "沈阳", "贵阳", "宁波",
"石家庄", "福州", "大连", "昆明", "苏州", "长沙", "温州", "银川", "太原", "厦门", "无锡", "咸阳", "唐山", "三亚", "西宁", "郑州", "扬州", "呼和浩特",
"兰州", "哈尔滨", "济南", "佛山", "长春", "青岛", "绵阳", "东莞", "威海", "吉林", "宜宾", "自贡", "邯郸", "合肥", "中山", "乌鲁木齐", "湛江", "烟台",
"廊坊", "潍坊", "保定", "攀枝花", "南宁", "秦皇岛", "延安", "常州", "丽江", "宜昌", "鞍山", "嘉兴", "大庆", "大理", "徐州", "镇江", "丹东", "六盘水",
"赣州", "芜湖", "南昌", "南通", "九江", "泰州", "洛阳", "台州", "惠州", "湖州", "泉州", "清远", "衢州", "江门", "绍兴", "宿迁", "海口", "珠海", "金华",
"连云港", "桂林", "马鞍山", "北海", "柳州", "淄博", "莆田", "盐城", "玉林", "玉溪", "本溪", "汕头", "肇庆", "曲靖", "衡阳", "新乡", "营口", "河源",
"黄石", "焦作", "揭阳", "茂名", "牡丹江", "盘锦", "平顶山", "韶关", "阳江", "梅州", "昆山", "襄阳", "株洲", "湘潭", "张家界", "潮州", "常熟", "安阳",
"云浮", "增城", "吴江", "瑞安", "乐清", "慈溪", "宁海", "奉化", "余姚", "温岭", "宜兴", "义乌", "舟山", "淮安" });
return Arrays.asList(new String[] { "上海", "北京", "广州", "深圳", "天津", "重庆", "成都", "西安", "杭州", "武汉", "南京", "沈阳", "贵阳", "宁波",
"石家庄", "福州", "大连", "昆明", "苏州", "长沙", "温州", "银川", "太原", "厦门", "无锡", "咸阳", "唐山", "三亚", "西宁", "郑州", "扬州", "呼和浩特",
"兰州", "哈尔滨", "济南", "佛山", "长春", "青岛", "绵阳", "东莞", "威海", "吉林", "宜宾", "自贡", "邯郸", "合肥", "中山", "乌鲁木齐", "湛江", "烟台",
"廊坊", "潍坊", "保定", "攀枝花", "南宁", "秦皇岛", "延安", "常州", "丽江", "宜昌", "鞍山", "嘉兴", "大庆", "大理", "徐州", "镇江", "丹东", "六盘水",
"赣州", "芜湖", "南昌", "南通", "九江", "泰州", "洛阳", "台州", "惠州", "湖州", "泉州", "清远", "衢州", "江门", "绍兴", "宿迁", "海口", "珠海", "金华",
"连云港", "桂林", "马鞍山", "北海", "柳州", "淄博", "莆田", "盐城", "玉林", "玉溪", "本溪", "汕头", "肇庆", "曲靖", "衡阳", "新乡", "营口", "河源",
"黄石", "焦作", "揭阳", "茂名", "牡丹江", "盘锦", "平顶山", "韶关", "阳江", "梅州", "昆山", "襄阳", "株洲", "湘潭", "张家界", "潮州", "常熟", "安阳",
"云浮", "增城", "吴江", "瑞安", "乐清", "慈溪", "宁海", "奉化", "余姚", "温岭", "宜兴", "义乌", "舟山", "淮安" });
}
}
@@ -20,7 +20,7 @@ import com.fangjia.mongo.dao.ServerAreaDao;
import com.fangjia.mongo.model.CalcCommand;
/**
* 商铺、写字楼出售均价计算
* 商铺、写字楼出售均价计算
*
* @author xiaoyu
*
@@ -115,7 +115,7 @@ public class SellShopOfficeCoredata {
}
List<String> citys = ServerAreaDao.getInstance().findAllCity();
//List<String> citys = Arrays.asList("北京","南京","天津","重庆","成都","大连","沈阳","哈尔滨","牡丹江","大庆","齐齐哈尔","佳木斯","伊春","鸡西","鹤岗","双鸭山","七台河","绥化","黑河");
//List<String> citys = Arrays.asList("北京","南京","天津","重庆","成都","大连","沈阳","哈尔滨","牡丹江","大庆","齐齐哈尔","佳木斯","伊春","鸡西","鹤岗","双鸭山","七台河","绥化","黑河");
if (citys == null) {
LOGGER.info("end. invalid calc.city!!s!");
return;
@@ -132,7 +132,7 @@ public class SellShopOfficeCoredata {
LOGGER.info("-----------------------------------------------------------------------------------");
for (String city : citys) {
if(city.equals("全国")){
if(city.equals("全国")){
continue;
}
// LOGGER.info("calc " + weekends.size() + " weekends of " + city);
@@ -54,8 +54,8 @@ public class SquareRentCoredata {
List<String> times = DateUtil.getStatMonths("2017-08-31","2017-08-31");
List<String> citys = Arrays.asList("上海");
//List<String> citys = ServerAreaDao.getInstance().findAllCity();//Arrays.asList("昆明");
List<String> citys = Arrays.asList("上海");
//List<String> citys = ServerAreaDao.getInstance().findAllCity();//Arrays.asList("昆明");
LOGGER.info("calc total city " + citys.size());
int index = 0;
@@ -72,9 +72,9 @@ public class SquareRentCoredata {
Coredata coredata = new Coredata(CalcDataCategoryEnum.RENT, city, calDate, SAMPLE_DAY, false, false);
// coredata.calcCitySqMetreRent();
// coredata.calcRegionSqMetreRent();//计算区域租金
coredata.calcDistrictSqMetreRent(30);//计算小区平米租金
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
// coredata.calcRegionSqMetreRent();//计算区域租金
coredata.calcDistrictSqMetreRent(30);//计算小区平米租金
LOGGER.info("-----------【"+index+"/"+citys.size()+"】---------------end calc " + CalcDataCategoryEnum.RENT + "-------------------");
System.out.println(new Date().toString());
}
@@ -30,7 +30,7 @@ public class Test {
public static void main(String[] args) throws Exception {
Date calcDate = DateUtil.parseDate("2013-11-10", "yyyy-MM-dd");
String city = "ÉϺ£";
String city = "上海";
int sampleDay = 365;
DataHolder dataHolder = new DataHolder(CalcDataCategoryEnum.SELL, city, calcDate, sampleDay, false);
@@ -41,7 +41,7 @@ public class Test {
CategoryEnum categoryEnum = CategoryEnum.DISTRICT;
DistrictKey districtKey = new DistrictKey(city, "ºç¿Ú", "¶«ËÄÐ¡Çø", categoryEnum, EstateTypeEnum.DISTRICT);
DistrictKey districtKey = new DistrictKey(city, "虹口", "东四小区", categoryEnum, EstateTypeEnum.DISTRICT);
Result res = calculator.calculatorDistrict(districtKey, calcDate, sampleDay);
operator.applyDistrict(districtKey, res);
@@ -172,9 +172,9 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
List<Integer> prices = ret.get(d.getRoom());
if(null == prices){
prices = new ArrayList<Integer>();
if((districtKey.getEstateTypeEnum().getEstateType().equals("小区") || districtKey.getEstateTypeEnum().getEstateType().equals("住宅")) && !d.isVilla()){
if((districtKey.getEstateTypeEnum().getEstateType().equals("小区") || districtKey.getEstateTypeEnum().getEstateType().equals("住宅")) && !d.isVilla()){
ret.put(d.getRoom(), prices);
}else if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅") && d.isVilla()){
}else if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅") && d.isVilla()){
ret.put(d.getRoom(), prices);
}
@@ -233,7 +233,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
//参与周边计算
//参与周边计算
// Map<Integer, List<Integer>> resultMap = provider.fetchAroundRoomAvgPriceData(districtKey, DateUtils.addMonths(calcDate, -1));
//
// for(int room : rooms){
@@ -314,24 +314,24 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
startDate = DateUtil.add(calcDate, sampleDay * (-1));
}
List<Result> result = new ArrayList<Result>();
//计算使用自身样本
//计算使用自身样本
result = calculateByOwn(districtKey, rooms, startDate, calcDate, sampleDay, result, regionMarkupMap);
//如果有自身样本计算出来的,则其它定可通过室与室之间的跨度比推算
//如果有自身样本计算出来的,则其它定可通过室与室之间的跨度比推算
if(result.size()>=1 && rooms.size()!=1){
result = calculateByRoomRatio(rooms, result, ratioMap, calcDate);
}
//使用周边物业类型,建筑类型 ,建筑年代的小区房源
//使用周边物业类型,建筑类型 ,建筑年代的小区房源
if(result.size() != rooms.size()){
result = calculateByArround(districtKey, rooms, startDate, calcDate, sampleDay, result);
}
//使用售价
//使用售价
if(result.size() != rooms.size()){
result = calculateByRatio(districtKey, rooms, startDate, calcDate, result);
}
//为没有计算出来的房型添加默认值
//为没有计算出来的房型添加默认值
if(result.size() != rooms.size()){
result = noCalculateRoom(districtKey, rooms, calcDate, result);
}
@@ -355,9 +355,9 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
Date yearAgo = DateUtil.add(calcDate, sampleDay*(-1));
Integer yearAgoNum = Integer.parseInt(DateUtil.formatToTightYYMMDD(DateUtil.truncateDay(yearAgo)));
String estateType = "小区";
if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅")){
estateType = "别墅";
String estateType = "小区";
if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅")){
estateType = "别墅";
}
Integer distAvgPrice = 0;
if (datas!=null && datas.size()>0) {
@@ -366,9 +366,9 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
List<Data> prices = ret.get(d.getRoom());
if(null == prices){
prices = new ArrayList<Data>();
if(estateType.equals("小区") && !d.isVilla()){
if(estateType.equals("小区") && !d.isVilla()){
ret.put(d.getRoom(), prices);
}else if(estateType.equals("别墅") && d.isVilla()){
}else if(estateType.equals("别墅") && d.isVilla()){
ret.put(d.getRoom(), prices);
}
}
@@ -413,7 +413,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
clu = DataCluster.cluster(prices);
}
//有房源
//有房源
if(clu != null && clu.getMedian()>0){
@@ -464,7 +464,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
private List<Result> calculateByRoomRatio(List<Integer> rooms, List<Result> results, Map<Integer, Double> ratioMap, Date calcDate){
List<Integer> allRooms = ServiceUtils.getAllRooms(rooms);
//找出最大可能可参照的室
//找出最大可能可参照的室
int standardRoom = 0;
double maxCredit = -1;
int maxCount = 0;
@@ -497,10 +497,10 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
}
Map<Integer, Integer> rentMap = new HashMap<Integer, Integer>();
//住前推价格
//住前推价格
for(int j=standardIndex-1;j>=0;j--){
int room = allRooms.get(j);
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
double ratio = ServiceUtils.getRatioByRoom(room + 1, ratioMap);
int knowRent = 0;
if(rentMap.containsKey(room+1)){
@@ -530,10 +530,10 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
}
}
//向后推价格
//向后推价格
for(int k=standardIndex+1;k<allRooms.size();k++){
int room = allRooms.get(k);
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
double ratio = ServiceUtils.getRatioByRoom(room, ratioMap);
int knowRent = 0;
if(rentMap.containsKey(room-1)){
@@ -594,7 +594,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
}
private List<Result> calculateByArround(DistrictKey districtKey, List<Integer> rooms, Date startDate, Date calcDate, int sampleDay, List<Result> results){
//参与周边计算
//参与周边计算
Map<Integer, List<Data>> resultMap = provider.fetchAroundRoomAvgPriceData(districtKey, startDate, calcDate);
if(resultMap.size() == 0){
return results;
@@ -690,7 +690,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
calcuateRooms.add(res.getKey());
}
Map<Integer, String> rentPriceMaps = provider.fetchRentSellStat(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), districtKey.getEstateTypeEnum().getEstateType(), startDate, calcDate);
//利用均价及已知租金,算得租售比进行计算
//利用均价及已知租金,算得租售比进行计算
for(int room : rooms){
if(!calcuateRooms.contains(room)){
Result res = getRentPriceResult(rentPriceMaps, SampleEnum.RATIO, room, calcDate);
@@ -763,12 +763,12 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
@Override
public List<Result> retryCalculatorDistrictRent(DistrictKey districtKey, int calcType, int houseType) {
//小区均价计算开始日期
//小区均价计算开始日期
@SuppressWarnings("deprecation")
Date firstDate = districtStatRentDao.findDistrictRentStatFirstWeekend(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), districtKey.getEstateTypeEnum().getEstateType());
//开始到现在所有月份的第一天
//开始到现在所有月份的第一天
List<String> dates = DateUtil.getStatMonths(DateUtil.formatByPattern(firstDate, "yyyy-MM-dd"), DateUtil.formatByPattern(DateUtil.getLastDayOfMonth(new Date(),-1),"yyyy-MM-dd"));
//查找指导价
//查找指导价
Map<String, Integer> guidingPriceMap = guidingPriceDao.findGuidingPrices(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), "district_rent");
List<Result> result = new ArrayList<Result>();
@@ -797,9 +797,9 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
if(null == prices){
prices = new ArrayList<Data>();
if((districtKey.getEstateTypeEnum().getEstateType().equals("小区") || districtKey.getEstateTypeEnum().getEstateType().equals("住宅")) && !d.isVilla()){
if((districtKey.getEstateTypeEnum().getEstateType().equals("小区") || districtKey.getEstateTypeEnum().getEstateType().equals("住宅")) && !d.isVilla()){
ret.put(d.getRoom(), prices);
}else if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅") && d.isVilla()){
}else if(districtKey.getEstateTypeEnum().getEstateType().equals("别墅") && d.isVilla()){
ret.put(d.getRoom(), prices);
}
}
@@ -830,7 +830,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
Result res = new Result();
res.setKey(room);
SampleEnum sampleEnum = SampleEnum.OWN;
//有房源
//有房源
if(clu != null && clu.getMean()>0){
res.setValue((int)clu.getUpperValue());
@@ -855,7 +855,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
result1.add(res);
}
//参与周边计算
//参与周边计算
/*if(res.getValue()==0){
Map<Integer, List<Integer>> resultMap = provider.fetchAroundRoomAvgPriceData(districtKey, startDate, endDate);
sampleEnum = SampleEnum.AROUND;
@@ -932,7 +932,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
/**
* 数量得分(最高得分0.1)
* 数量得分(最高得分0.1)
*
* @param points
* @return
@@ -941,14 +941,14 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
if (points.size() == 0) {
return 0;
}
// 每100个样本=0.01
// 每100个样本=0.01
double c1 = (double) points.size() / 100.0 / 100.0;
c1 = (c1 > 0.1 ? 0.1 : c1);
return c1;
}
/**
* 质量得分(最高得分0.1)
* 质量得分(最高得分0.1)
*
* @param points
* @return
@@ -964,21 +964,21 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
for (Data p : points) {
int calcTime = Integer.parseInt(DateUtil.formatToTightYYMMDD(DateUtil.truncateDay(calcDate)));
long diff = calcTime - p.getDate();
if (diff <= 30 * 24 * 3600 * 1000L) {// 一个月内
if (diff <= 30 * 24 * 3600 * 1000L) {// 一个月内
c2 = c2 + perc * 1.00d;
} else if (diff <= 60 * 24 * 3600 * 1000L) {// 两个月内
} else if (diff <= 60 * 24 * 3600 * 1000L) {// 两个月内
c2 = c2 + perc * 0.90d;
} else if (diff <= 90 * 24 * 3600 * 1000L) {// 三个月内
} else if (diff <= 90 * 24 * 3600 * 1000L) {// 三个月内
c2 = c2 + perc * 0.85d;
} else if (diff <= 180 * 24 * 3600 * 1000L) {// 半年内
} else if (diff <= 180 * 24 * 3600 * 1000L) {// 半年内
c2 = c2 + perc * 0.80d;
} else if (diff <= 365 * 24 * 3600 * 1000L) {// 一年内
} else if (diff <= 365 * 24 * 3600 * 1000L) {// 一年内
c2 = c2 + perc * 0.70d;
} else if (diff <= 540 * 24 * 3600 * 1000L) {// 一年半内
} else if (diff <= 540 * 24 * 3600 * 1000L) {// 一年半内
c2 = c2 + perc * 0.60d;
} else if (diff <= 720 * 24 * 3600 * 1000L) {// 两年内
} else if (diff <= 720 * 24 * 3600 * 1000L) {// 两年内
c2 = c2 + perc * 0.40d;
} else {// 超过两年
} else {// 超过两年
c2 = c2 + perc * 0.10d;
}
}
@@ -1040,7 +1040,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
DataManager dataManager = provider.fetchDataByDistrict2(districtKey, startDate, calcDate);
List<Data> datas = dataManager.applyTimeFactorPoints(dataManager.getDatas(), calcDate);
SqRentResult res = calculateByOwn(datas, calcDate, SampleType.OWN, CALC_OWN_BASE_CREDIT, sampleDay);
//根据周边相似均价的小区的租房房源
//根据周边相似均价的小区的租房房源
if(res == null){
res = calculateDistrictSqMetreByArround(districtKey, null, calcDate, sampleDay);
}
@@ -1077,7 +1077,7 @@ public class RentHouseAverageCalculator extends AbstractCalculator{
private SqRentResult calculateDistrictSqMetreByArround(DistrictKey districtKey, Date startDate, Date calcDate, int sampleDay){
//参与周边计算
//参与周边计算
List<Double> datas = provider.fetchAroundData(districtKey, startDate, calcDate, 500, null);
if(null == datas || datas.size()==0){
datas = provider.fetchAroundData(districtKey, startDate, calcDate, 1000, 500);
@@ -106,7 +106,7 @@ public class RentShopOfficeAverageCalculator extends AbstractCalculator {
// }
//¸ù¾ÝÖܱ߼ÆËã
//根据周边计算
// if ((clu == null || clu.getUpperValue() == 0) && res==null) {
//
// List<Integer> points = provider.fetchAroundAvgPriceData(districtKey);
@@ -18,7 +18,7 @@ import com.fangjia.coredata.price.util.NumberUtils;
import com.fangjia.mongo.model.RegionStat;
/**
* 小区均价计算实现
* 小区均价计算实现
*
* @author xiaoyu
*
@@ -56,7 +56,7 @@ public class SellHouseAverageCalculator extends AbstractCalculator {
SampleEnum sampleEnum = SampleEnum.OWN;
DataManager dataManager = provider.fetchData(districtKey);
// 这个小区存在指导价
// 这个小区存在指导价
if (dataManager.isExistGuidingPrice(districtKey)) {
List<Integer> points = dataManager.getPointsByFactor(districtKey, calcDate);
clu = DataCluster.cluster(points);
@@ -54,7 +54,7 @@ public class SellShopOfficeAverageCalculator extends AbstractCalculator {
Cluster clu = null;
Result res = null;
//房源计算
//房源计算
if (dataManager.getDataSize() > 0) {
sampleEnum = SampleEnum.OWN;
List<Integer> points = dataManager.getPoints();
@@ -83,7 +83,7 @@ public class SellShopOfficeAverageCalculator extends AbstractCalculator {
}
}
//根据路名计算价格
//根据路名计算价格
// if ((clu == null || clu.getUpperValue() == 0) && res==null) {
// if(CategoryEnum.SHOP.equals(districtKey.getCategoryEnum())){
// if(null!=districtKey.getAddress()&&StringUtils.isNotBlank(districtKey.getAddress())){
@@ -114,7 +114,7 @@ public class SellShopOfficeAverageCalculator extends AbstractCalculator {
//
// }
//根据周边计算
//根据周边计算
if ((clu == null || clu.getUpperValue() == 0) && res==null) {
List<Integer> points = provider.fetchAroundAvgPriceData(districtKey, calcDate);
@@ -68,7 +68,7 @@ public class CoredataConfig {
}
/**
* ÊÇ·ñ°ÑÊý¾Ý·ÅÈëÄÚ´æÖÐ
* 是否把数据放入内存中
*
* @return
*/
@@ -10,7 +10,7 @@ import com.fangjia.coredata.price.util.CalcException;
import com.fangjia.mongo.model.RegionStat;
/**
* 均价计算接口
* 均价计算接口
*
* @author xiaoyu
*
@@ -18,7 +18,7 @@ import com.fangjia.mongo.model.RegionStat;
public interface Calculator {
/**
* 计算城市均价
* 计算城市均价
*
* @param cityKey
* @param calcDate
@@ -29,7 +29,7 @@ public interface Calculator {
public Result calculatorCity(CityKey cityKey, Date calcDate, int sampleDay) throws CalcException;
/**
* 计算城市平米租金
* 计算城市平米租金
* @param cityKey
* @param calcDate
* @param sampleDay
@@ -39,7 +39,7 @@ public interface Calculator {
public SqRentResult calculatorRegionSqMetreRent(CityKey cityKey, Date calcDate, int sampleDay);
public SqRentResult calculatorDistrictSqMetreRent(DistrictKey districtKey,Date calcDate, int sampleDay, double rentRatio, Map<String, Map<String, Double>> regionMarkupMap, RegionStat cityRegionStat);
/**
* 计算小区均价
* 计算小区均价
* R
* @param districtKey
* @param calcDate
@@ -51,7 +51,7 @@ public interface Calculator {
/**
* 计算小区租金
* 计算小区租金
* @param districtKey
* @param calcDate
* @param sampleDay
@@ -6,20 +6,20 @@ import java.util.List;
import com.fangjia.coredata.price.util.NumberUtils;
public class Cluster {
// 价格差偏移量
// 价格差偏移量
public static final double MIN_VALUE_OFFSET = 0.2d;
public static final double UPPER_VALUE_OFFSET = 0.2d;
public static final double LOWER_VALUE_OFFSET = 0.1d;
private double mean; // 均值
private double median; // 中位数
private double upperValue; // 偏大值
private double lowerValue; // 偏小值
private double centerValue; // 中心值
private double mean; // 均值
private double median; // 中位数
private double upperValue; // 偏大值
private double lowerValue; // 偏小值
private double centerValue; // 中心值
private int sampleSize; // 样本数量
private int sampleSize; // 样本数量
private double[][] cluters;
public Cluster(double[][] cluters) {
@@ -24,7 +24,7 @@ import com.fangjia.mongo.model.GuidingPrice;
import com.fangjia.mongo.model.RegionStat;
/**
* 数据管理
* 数据管理
*
* @author xiaoyu
*
@@ -100,7 +100,7 @@ public class DataManager {
/**
* <pre>
* 获取可计算的points,加入了时间因素和后台影响因素
* 获取可计算的points,加入了时间因素和后台影响因素
* </pre>
*
* @param districtKey
@@ -112,13 +112,13 @@ public class DataManager {
}
/**
* 数据的指导价格影响 越接近计算时间的数据,影响权重越大
* 数据的指导价格影响 越接近计算时间的数据,影响权重越大
*
* <pre>
* 1.样本不充足,则使用城市的平均涨跌幅得出计算点
* 2.样本充足,则影响由两部分数据组成
* (1) 样本本身影响因素占(1 - GUIDING_PERCENT)
* (2) 指导价影响因素占GUIDING_PERCENT * y∈[0-1](计算日期离指导价日期越近,指导价的影响权重越大)
* 1.样本不充足,则使用城市的平均涨跌幅得出计算点
* 2.样本充足,则影响由两部分数据组成
* (1) 样本本身影响因素占(1 - GUIDING_PERCENT)
* (2) 指导价影响因素占GUIDING_PERCENT * y∈[0-1](计算日期离指导价日期越近,指导价的影响权重越大)
* </pre>
*
* @param dataList
@@ -135,13 +135,13 @@ public class DataManager {
List<GuidingPrice> guidingPrices = guidingPriceDao.findGuidingPrice(districtKey.getCity(), districtKey.getRegion(),
districtKey.getName(), districtKey.getCategoryEnum().getCategory(), districtKey.getEstateTypeEnum()
.getEstateType());
// 如果没有指导价,则直接返回
// 如果没有指导价,则直接返回
if (guidingPrices == null || guidingPrices.size() == 0) {
return ret;
}
/**
* 如果指导价存在并且样本不充足,则使用城市的平均涨跌幅得出计算点
* 如果指导价存在并且样本不充足,则使用城市的平均涨跌幅得出计算点
*/
if (dataList.size() < 10) {
int point = getPointByCityTrend(guidingPrices, districtKey, calcDate);
@@ -150,18 +150,18 @@ public class DataManager {
}
} else {
/**
* 样本充足,则影响价格由两部分数据组成
* 样本充足,则影响价格由两部分数据组成
*
* <pre>
* (1) 样本本身影响因素占(1 - GUIDING_PERCENT)
* (2) 指导价影响因素占GUIDING_PERCENT * y∈[0-1](计算日期离指导价日期越近,指导价的影响权重越大)
* (1) 样本本身影响因素占(1 - GUIDING_PERCENT)
* (2) 指导价影响因素占GUIDING_PERCENT * y∈[0-1](计算日期离指导价日期越近,指导价的影响权重越大)
* </pre>
*/
int c = (int) ((GUIDING_PERCENT * dataList.size()) / (1 - GUIDING_PERCENT));
long calcMills = calcDate.getTime();
for (GuidingPrice gp : guidingPrices) {
long diffMills = Math.abs(gp.getGuidingDate().getTime() - calcMills);
// 计算日期离指导价日期越近,指导价的影响权重越大
// 计算日期离指导价日期越近,指导价的影响权重越大
if (diffMills <= MONTH_MILLS) {
c = c * 1;
} else if (diffMills <= 2 * MONTH_MILLS) {
@@ -191,7 +191,7 @@ public class DataManager {
}
/**
* 数据的时间影响因素 越接近计算时间的数据,将会复制出更多
* 数据的时间影响因素 越接近计算时间的数据,将会复制出更多
*
* @param dataList
* @param calcDate
@@ -218,7 +218,7 @@ public class DataManager {
Date publishDate = FORMAT.parse(String.valueOf(d));
long diffMills = calcDate.getTime() - publishDate.getTime();
int repeat = 0;
// 加大最近房源的计算量,以达到提高最近房源权重的目的
// 加大最近房源的计算量,以达到提高最近房源权重的目的
if (diffMills <= 3 * WEEK_MILLS) {
repeat = 5;
} else if (diffMills <= MONTH_MILLS) {
@@ -245,7 +245,7 @@ public class DataManager {
private int getPointByCityTrend(List<GuidingPrice> guidingPrices, DistrictKey districtKey, Date calcDate) {
GuidingPrice guidingPrice = guidingPrices.get(0);
// 选出最接近计算日期的一条指导价
// 选出最接近计算日期的一条指导价
for (GuidingPrice gp : guidingPrices) {
long diff1 = gp.getGuidingDate().getTime() - calcDate.getTime();
long diff2 = guidingPrice.getGuidingDate().getTime() - calcDate.getTime();
@@ -11,7 +11,7 @@ import com.fangjia.coredata.price.util.ApplyException;
public interface Operator {
/**
* 城市计算结果应用
* 城市计算结果应用
*
* @param cityKey
* @param result
@@ -20,7 +20,7 @@ public interface Operator {
public void applyCity(CityKey cityKey, Result result, String category) throws ApplyException;
/**
* 小区计算结果应用
* 小区计算结果应用
*
* @param districtKey
* @param result
@@ -30,7 +30,7 @@ public interface Operator {
/**
* 小区租金计算结果应用
* 小区租金计算结果应用
*
* @param districtKey
* @param result
@@ -42,7 +42,7 @@ public interface Operator {
/**
* 计算区域租金
* 计算区域租金
* @param regions
* @param calDate
*/
@@ -9,7 +9,7 @@ import com.fangjia.coredata.dao.DistrictKey;
import com.fangjia.coredata.price.tree.Data;
/**
* 数据提供者
* 数据提供者
*
* @author xiaoyu
*
@@ -17,7 +17,7 @@ import com.fangjia.coredata.price.tree.Data;
public interface Provider {
/**
* 获取城市数据
* 获取城市数据
*
* @param cityKey
* @return
@@ -27,7 +27,7 @@ public interface Provider {
public DataManager fetchRegionRentData(CityKey cityKey, Date startDate);
/**
* 获取小区数据
* 获取小区数据
*
* @param districtKey
* @return
@@ -35,7 +35,7 @@ public interface Provider {
public DataManager fetchData(DistrictKey districtKey);
/**
* 获取指定小区周边的数据
* 获取指定小区周边的数据
*
* @param districtKey
* @return
@@ -45,7 +45,7 @@ public interface Provider {
/**
* 获取周边小区的均价数据
* 获取周边小区的均价数据
* @param districtKey
* @return
*/
@@ -53,7 +53,7 @@ public interface Provider {
public List<Integer> fetchAroundAvgPriceData(DistrictKey districtKey, Date calcDate);
/**
* 获取周边小区按不同室的均价数据
* 获取周边小区按不同室的均价数据
* @param districtKey
* @return
*/
@@ -64,7 +64,7 @@ public interface Provider {
public List<Double> fetchAroundData(DistrictKey districtKey, Date startDate, Date endDate, Integer radio, Integer minRadio);
public List<Double> fetchAroundHouseData(DistrictKey districtKey, Date startDate, Date endDate, Integer radio, Integer minRadio);
/**
* 根据小区查询相关数据
* 根据小区查询相关数据
* @param districtKey
* @return
*/
@@ -3,13 +3,13 @@ package com.fangjia.coredata.price.core;
import java.util.Date;
public class Result {
private int sampleSize; // 样本数量
private SampleEnum sampleEnum; // 样本类型
private int value; // 运算出的值
private int sampleSize; // 样本数量
private SampleEnum sampleEnum; // 样本类型
private int value; // 运算出的值
private Date calcDate;
private double credit; // 可信度
private int mean; // 均值
private int key;//值对应该的key,非必需。如(租金计算中的room)
private double credit; // 可信度
private int mean; // 均值
private int key;//值对应该的key,非必需。如(租金计算中的room)
private String sampleRange;
private int oldValue;
@@ -100,14 +100,14 @@ public class Result {
public enum SampleEnum {
OWN("own"), // 自身样本
GUI("gui"), // 指导价
AROUND("around"), // 周边样本
MIX("mix"), // 混合
NONE("none"), // 无样本
RATIO("ratio"), // 根据均价推算
ROOMRATIO("room_ratio"), // 根据房型跨度推算
CORRECTED("corrected"), // 价格修改,根据房型修正
OWN("own"), // 自身样本
GUI("gui"), // 指导价
AROUND("around"), // 周边样本
MIX("mix"), // 混合
NONE("none"), // 无样本
RATIO("ratio"), // 根据均价推算
ROOMRATIO("room_ratio"), // 根据房型跨度推算
CORRECTED("corrected"), // 价格修改,根据房型修正
;
private final String sampleType;
@@ -5,13 +5,13 @@ import java.util.Date;
import com.fangjia.coredata.price.core.Result.SampleEnum;
public class SqRentResult {
private int sampleSize; // 样本数量
private SampleType sampleEnum; // 样本类型
private double value; // 运算出的值
private int sampleSize; // 样本数量
private SampleType sampleEnum; // 样本类型
private double value; // 运算出的值
private Date calcDate;
private double credit; // 可信度
private double mean; // 均值
private int key;//值对应该的key,非必需。如(租金计算中的room)
private double credit; // 可信度
private double mean; // 均值
private int key;//值对应该的key,非必需。如(租金计算中的room)
private String sampleRange;
private double oldValue;
@@ -102,15 +102,15 @@ public class SqRentResult {
public enum SampleType {
OWN("own"), // 自身样本
GUI("gui"), // 指导价
AROUND("around"), // 周边样本
MIX("mix"), // 混合
NONE("none"), // 无样本
RATIO("ratio"), // 根据均价推算
HISTORY("history"), // 根据均价推算
ROOMRATIO("room_ratio"), // 根据房型跨度推算
CORRECTED("corrected"), // 价格修改,根据房型修正
OWN("own"), // 自身样本
GUI("gui"), // 指导价
AROUND("around"), // 周边样本
MIX("mix"), // 混合
NONE("none"), // 无样本
RATIO("ratio"), // 根据均价推算
HISTORY("history"), // 根据均价推算
ROOMRATIO("room_ratio"), // 根据房型跨度推算
CORRECTED("corrected"), // 价格修改,根据房型修正
;
private final String sampleType;
@@ -52,11 +52,11 @@ public class RentHouseResultOperator implements Operator {
private RegionStatDao regionStatDao = RegionStatDao.getInstance();
public static final double MIN_VALID_MARKUP = 0.003d; // 每月最小有效涨跌幅0.3%
public static final double MIN_VALID_MARKUP = 0.003d; // 每月最小有效涨跌幅0.3%
public static final double MAX_VALID_MARKUP = 0.02d; // 每月最小有效涨跌幅2%
public static final double MAX_VALID_MARKUP = 0.02d; // 每月最小有效涨跌幅2%
public static final double INVALID_MARKUP = 0.06d; // 每月大有效涨跌幅6%
public static final double INVALID_MARKUP = 0.06d; // 每月大有效涨跌幅6%
public static final int AVG_MARKUP_WEEKEND = 6;
@@ -94,7 +94,7 @@ public class RentHouseResultOperator implements Operator {
for (Result res : result) {
int curMonthPrice = res.getValue();
DistrictStatRent rent = lastRentStatMap.get(res.getKey());// 历史房型价格
DistrictStatRent rent = lastRentStatMap.get(res.getKey());// 历史房型价格
Integer lastMonthPrice = null;
if(rent != null){
lastMonthPrice = rent.getAvgPrice();
@@ -106,7 +106,7 @@ public class RentHouseResultOperator implements Operator {
DistrictStatRent districtStatRent = new DistrictStatRent();
districtStatRent.setHouseCount(res.getSampleSize());
if (null == lastMonthPrice && curMonthPrice > 0) {//没有历史,第一次计算有值
if (null == lastMonthPrice && curMonthPrice > 0) {//没有历史,第一次计算有值
districtStatRent.setMarkup(0);
districtStatRent.setAvgPrice(curMonthPrice);
} else {
@@ -148,7 +148,7 @@ public class RentHouseResultOperator implements Operator {
+ res.getSampleSize() + " markup:" + districtStatRent.getMarkup()+" credit:"+districtStatRent.getCredit());
}
//填充缺失的室
//填充缺失的室
//fillRoomPrice(rentStats);
rentStats = correctRentPrice(rentStats, lastRentStatMap, ratioMap);
@@ -195,7 +195,7 @@ public class RentHouseResultOperator implements Operator {
}
if(Math.abs(markup) > 1500 || prePrice== null){
// 随机[-2~1)的涨跌幅
// 随机[-2~1)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * -3 + 1);
double tempMarkup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
@@ -282,25 +282,25 @@ public class RentHouseResultOperator implements Operator {
}
/**
* 检查涨跌幅是否正常
* 检查涨跌幅是否正常
*
* @param markup
* @param avgMarkup
* @return
*/
private boolean isValidMarkup(double markup, double avgMarkup) {
// 每周涨跌1%属于正常
// 每周涨跌1%属于正常
if (Math.abs(markup) > MIN_VALID_MARKUP && Math.abs(markup) < MAX_VALID_MARKUP) {
return true;
}
// 每周涨跌7%属于不正常
// 每周涨跌7%属于不正常
if (Math.abs(markup) > INVALID_MARKUP) {
return false;
}
// if (avgMarkup < MIN_VALID_MARKUP) {
// return false;
// }
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// if (Math.abs(markup) > (avgMarkup + avgMarkup *
// MAX_AVG_MARKUP_FLOAT)) {
// return false;
@@ -315,7 +315,7 @@ public class RentHouseResultOperator implements Operator {
Map<String, Map<Integer, List<Integer>>> regionMap = groupRegionRoom(districtStatRents);
int rooms = 5;
for (String region : regions) {
// if(!region.equals("双流")){
// if(!region.equals("双流")){
// continue;
// }
Map<Integer, List<Integer>> roomMap = regionMap.get(region);
@@ -388,7 +388,7 @@ public class RentHouseResultOperator implements Operator {
roomMap.put(rentStat.getHouseType(), prices);
}
if(StringUtils.isNotBlank(rentStat.getEstateType()) && !rentStat.getEstateType().equals("别墅")){
if(StringUtils.isNotBlank(rentStat.getEstateType()) && !rentStat.getEstateType().equals("别墅")){
prices.add(rentStat.getAvgPrice());
}
@@ -412,7 +412,7 @@ public class RentHouseResultOperator implements Operator {
}
/**
* 修正租金(户型大租金反而低的、或者户型租金不匹配的)
* 修正租金(户型大租金反而低的、或者户型租金不匹配的)
*/
private List<DistrictStatRent> correctRentPrice(List<DistrictStatRent> stats, Map<Integer, DistrictStatRent> lastRentStatMap, Map<Integer, Double> ratioMap) {
if (CollectionUtils.isEmpty(stats) || stats.size() == 1) {
@@ -430,7 +430,7 @@ public class RentHouseResultOperator implements Operator {
rooms.add(rent.getHouseType());
}
List<Integer> allRooms = ServiceUtils.getAllRooms(rooms);
//找出最大可能可参照的室
//找出最大可能可参照的室
int standardRoom = 0;
double maxCredit = -1;
int maxCount = 0;
@@ -468,10 +468,10 @@ public class RentHouseResultOperator implements Operator {
}
Map<Integer, Integer> rentMap = new HashMap<Integer, Integer>();
//住前推价格
//住前推价格
for(int j=standardIndex-1;j>=0;j--){
int room = allRooms.get(j);
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
double ratio = ServiceUtils.getRatioByRoom(room + 1, ratioMap);
int knowRent = 0;
if(rentMap.containsKey(room+1)){
@@ -501,10 +501,10 @@ public class RentHouseResultOperator implements Operator {
}
}
//向后推价格
//向后推价格
for(int k=standardIndex+1;k<allRooms.size();k++){
int room = allRooms.get(k);
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
if(!calcalatedMap.containsKey(room)){//是否根据房源已计算
double ratio = ServiceUtils.getRatioByRoom(room, ratioMap);
int knowRent = 0;
if(rentMap.containsKey(room-1)){
@@ -552,7 +552,7 @@ public class RentHouseResultOperator implements Operator {
return 0;
}
int markup = 0;
DistrictStatRent rent = lastRentStatMap.get(room);// 历史房型价格
DistrictStatRent rent = lastRentStatMap.get(room);// 历史房型价格
Integer lastMonthPrice = null;
if(rent != null){
@@ -571,7 +571,7 @@ public class RentHouseResultOperator implements Operator {
return;
}
// 补全户型均价
// 补全户型均价
int maxRoom = 0;
for (DistrictStatRent rentStat : stats) {
if (rentStat.getHouseType() > maxRoom) {
@@ -667,7 +667,7 @@ public class RentHouseResultOperator implements Operator {
}
i++;
DistrictStatRent rent = roomPriceMap.get(res.getKey());// 历史房型价格
DistrictStatRent rent = roomPriceMap.get(res.getKey());// 历史房型价格
Integer lastMonthPrice = null;
if(rent != null){
lastMonthPrice = rent.getAvgPrice();
@@ -680,7 +680,7 @@ public class RentHouseResultOperator implements Operator {
DistrictStatRent districtStatRent = new DistrictStatRent();
districtStatRent.setHouseCount(res.getSampleSize());
if (null == lastMonthPrice && curMonthPrice > 0) {//没有历史,第一次计算有值
if (null == lastMonthPrice && curMonthPrice > 0) {//没有历史,第一次计算有值
districtStatRent.setMarkup(0);
districtStatRent.setAvgPrice(curMonthPrice);
} else {
@@ -691,11 +691,11 @@ public class RentHouseResultOperator implements Operator {
} else if (null != lastMonthPrice && curMonthPrice > 0) {
markup = (double) (curMonthPrice - lastMonthPrice) / lastMonthPrice;
// 最近6周的平均涨跌幅
// 最近6周的平均涨跌幅
avgMarkup = districtStatRentDao.findLatestStatAvgMarkup(districtKey.getCity(), districtKey.getRegion(),
districtKey.getName(),districtKey.getEstateTypeEnum().getEstateType(), res.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
int level = checkHouseReliability(districtStatRent.getHouseCount());
@@ -715,7 +715,7 @@ public class RentHouseResultOperator implements Operator {
}
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastMonthPrice == curMonthPrice) {
if (RandomUtil.nextBoolean()) {
curMonthPrice = (int) (curMonthPrice - curMonthPrice * (RandomUtil.random(3, 15) / 1000d));
@@ -843,7 +843,7 @@ public class RentHouseResultOperator implements Operator {
double curValue = 0;
int curMarkup = 0;
if(null == res){//本次无计算结果,但有历史
if(null == res){//本次无计算结果,但有历史
//curMarkup = getAvgMarkup(sqmetreRegionRents);
double lastMonthPrice = sqmetreRegionRents.get(sqmetreRegionRents.size()-1).getAvgPrice();
@@ -851,8 +851,8 @@ public class RentHouseResultOperator implements Operator {
curMarkup = (int) (bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()*100);
curValue = (int)(lastMonthPrice + lastMonthPrice*curMarkup/10000);
}else{//本次有计算结果
if(sqmetreRegionRents.size()==0){//无历史
}else{//本次有计算结果
if(sqmetreRegionRents.size()==0){//无历史
curValue = res.getValue();
}else{
double lastMonthPrice = sqmetreRegionRents.get(sqmetreRegionRents.size()-1).getAvgPrice();
@@ -860,7 +860,7 @@ public class RentHouseResultOperator implements Operator {
if(curMarkup>-500 && curMarkup<500){
curValue = res.getValue();
}else{
//是否利用均价涨跌幅
//是否利用均价涨跌幅
RegionStat regionStat = regionStatDao.findLastRegionStat(city, region, null);
if(null != regionStat){
if(regionStat.getWeekendMarkup()>=0 && curMarkup>0){
@@ -1020,7 +1020,7 @@ public class RentHouseResultOperator implements Operator {
}
if(Math.abs(markup) > 450 || prePrice== null){
// 随机[-2~1)的涨跌幅
// 随机[-2~1)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * -0.3 +0.3);
double tempMarkup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
@@ -33,11 +33,11 @@ public class RentShopOfficeResultOperator implements Operator{
private RentStatDao rentStatDao = RentStatDao.getInstance();
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double INVALID_MARKUP = 0.06d; // 每周最大有效涨跌幅6%
public static final double INVALID_MARKUP = 0.06d; // 每周最大有效涨跌幅6%
public static final int AVG_MARKUP_WEEKEND = 6;
@@ -84,16 +84,16 @@ public class RentShopOfficeResultOperator implements Operator{
if (lastRegionStat != null && lastRegionStat.getAvgPrice() > 0) {
double markup = (double) (value - lastRegionStat.getAvgPrice()) / (double) lastRegionStat.getAvgPrice();
// 最近4周的平均涨跌幅
// 最近4周的平均涨跌幅
avgMarkup = businessRegionStatDao.findLatestStatAvgMarkup(city, region, block, category, result.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
double realMarkup = balanceMarkup(markup, avgMarkup);
value = (int) (lastRegionStat.getAvgPrice() + lastRegionStat.getAvgPrice() * realMarkup);
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastRegionStat.getAvgPrice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -149,7 +149,7 @@ public class RentShopOfficeResultOperator implements Operator{
}
}
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
if (value == 0 && lastStat != null) {
value = lastStat.getWeekendAvgprice();
}
@@ -158,11 +158,11 @@ public class RentShopOfficeResultOperator implements Operator{
double avgMarkup = 0;
if (lastStat != null && lastStat.getWeekendAvgprice() > 0) {
double markup = (double) (value - lastStat.getWeekendAvgprice()) / (double) lastStat.getWeekendAvgprice();
// 最近6周的平均涨跌幅
// 最近6周的平均涨跌幅
avgMarkup = rentStatDao.findLatestStatAvgMarkup(districtKey.getCity(), districtKey.getRegion(),
districtKey.getName(), districtKey.getCategoryEnum(), result.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
int level = checkHouseReliability(result.getSampleSize());
@@ -180,7 +180,7 @@ public class RentShopOfficeResultOperator implements Operator{
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastStat.getWeekendAvgprice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -221,7 +221,7 @@ public class RentShopOfficeResultOperator implements Operator{
if(rentStat.getWeekendAvgprice() > 15){
rentStatDao.saveOrUpdateRentStat(rentStat);
}else{
//删除月平米租金小于60的数据
//删除月平米租金小于60的数据
rentStatDao.deleteRentStatByParams(rentStat.getCity(), rentStat.getRegion(), rentStat.getName(), rentStat.getKind(), 15);
}
@@ -241,9 +241,9 @@ public class RentShopOfficeResultOperator implements Operator{
private double getOtherWebsitePrice(DistrictKey districtKey){
AverageStatistics averageStatistics = null;
if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
averageStatistics = averageStatisticsDao.findLatestAverageStatistics(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), CategoryEnum.OFFICE.getCategory());
}else if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
}else if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
averageStatistics = averageStatisticsDao.findLatestAverageStatistics(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), CategoryEnum.SHOP.getCategory());
}
@@ -339,7 +339,7 @@ public class RentShopOfficeResultOperator implements Operator{
}
if(Math.abs(tempMarkup)>3){
// 随机[-0.5~1.5)的涨跌幅
// 随机[-0.5~1.5)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * -1+0.5);
double markup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
Integer newPrice = newPrices.get(k+1);
@@ -367,7 +367,7 @@ public class RentShopOfficeResultOperator implements Operator{
}
if(Math.abs(tempMarkup)>3){
// 随机[0~2)的涨跌幅
// 随机[0~2)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * 2);
double markup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
int avg_price = (int) (newPrices.get(j-1) * (1 + markup / 100));
@@ -381,9 +381,9 @@ public class RentShopOfficeResultOperator implements Operator{
}
//更新价格
//更新价格
if(isUpdate){
System.out.println(" 修正后: " +newPrices.toString());
System.out.println(" 修正后: " +newPrices.toString());
for(int m = 0;m < weekends.size(); m++){
String weekend = weekends.get(m);
Integer newPrice = newPrices.get(m);
@@ -443,25 +443,25 @@ public class RentShopOfficeResultOperator implements Operator{
}
/**
* 检查涨跌幅是否正常
* 检查涨跌幅是否正常
*
* @param markup
* @param avgMarkup
* @return
*/
private boolean isValidMarkup(double markup, double avgMarkup) {
// 每周涨跌1%属于正常
// 每周涨跌1%属于正常
if (Math.abs(markup) > MIN_VALID_MARKUP && Math.abs(markup) < MAX_VALID_MARKUP) {
return true;
}
// 每周涨跌7%属于不正常
// 每周涨跌7%属于不正常
if (Math.abs(markup) > INVALID_MARKUP) {
return false;
}
// if (avgMarkup < MIN_VALID_MARKUP) {
// return false;
// }
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// if (Math.abs(markup) > (avgMarkup + avgMarkup * MAX_AVG_MARKUP_FLOAT)) {
// return false;
// }
@@ -24,11 +24,11 @@ import com.fangjia.mongo.model.DistrictStat;
import com.fangjia.mongo.model.RegionStat;
public class SellHouseResultOperator implements Operator {
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double INVALID_MARKUP = 0.07d; // 每周最大有效涨跌幅7%
public static final double INVALID_MARKUP = 0.07d; // 每周最大有效涨跌幅7%
public static final int AVG_MARKUP_WEEKEND = 6;
@@ -56,19 +56,19 @@ public class SellHouseResultOperator implements Operator {
regionStat.setCity(city);
regionStat.setRegion(region);
regionStat.setBlock(block);
regionStat.setCat("板块");
regionStat.setCat("板块");
lastRegionStat = regionStatDao.findRegionStat(city, region, block, DateUtil.getLastSunday(result.getCalcDate()));
} else if (city != null && region != null && block == null) {
regionStat.setCity(city);
regionStat.setRegion(region);
regionStat.setBlock(null);
regionStat.setCat("区域");
regionStat.setCat("区域");
lastRegionStat = regionStatDao.findRegionStat(city, region, null, DateUtil.getLastSunday(result.getCalcDate()));
} else if (city != null && region == null && block == null) {
regionStat.setCity(city);
regionStat.setRegion(null);
regionStat.setBlock(null);
regionStat.setCat("城市");
regionStat.setCat("城市");
lastRegionStat = regionStatDao.findRegionStat(city, null, null, DateUtil.getLastSunday(result.getCalcDate()));
} else {
return;
@@ -79,16 +79,16 @@ public class SellHouseResultOperator implements Operator {
if (lastRegionStat != null && lastRegionStat.getAvgPrice() > 0) {
double markup = (double) (value - lastRegionStat.getAvgPrice()) / (double) lastRegionStat.getAvgPrice();
// 最近4周的平均涨跌震荡
// 最近4周的平均涨跌震荡
avgMarkup = regionStatDao.findLatestStatAvgShake(city, region, block, result.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
double realMarkup = balanceMarkup(markup, avgMarkup);
value = (int) (lastRegionStat.getAvgPrice() + lastRegionStat.getAvgPrice() * realMarkup);
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastRegionStat.getAvgPrice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -151,7 +151,7 @@ public class SellHouseResultOperator implements Operator {
return;
}
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
if (value == 0) {
value = lastStat.getAvgPrice();
}
@@ -159,18 +159,18 @@ public class SellHouseResultOperator implements Operator {
double avgMarkup = 0;
if (lastStat != null && lastStat.getAvgPrice() > 0) {
double markup = (double) (value - lastStat.getAvgPrice()) / (double) lastStat.getAvgPrice();
// 最近6周的平均涨跌幅
// 最近6周的平均涨跌幅
avgMarkup = districtStatDao
.findLatestStatAvgMarkup(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), districtKey
.getEstateTypeEnum().getEstateType(), res.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
double realMarkup = balanceMarkup(markup, avgMarkup);
value = (int) (lastStat.getAvgPrice() + lastStat.getAvgPrice() * realMarkup);
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastStat.getAvgPrice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -212,25 +212,25 @@ public class SellHouseResultOperator implements Operator {
}
/**
* 检查涨跌幅是否正常
* 检查涨跌幅是否正常
*
* @param markup
* @param avgMarkup
* @return
*/
private boolean isValidMarkup(double markup, double avgMarkup) {
// 每周涨跌1%属于正常
// 每周涨跌1%属于正常
if (Math.abs(markup) > MIN_VALID_MARKUP && Math.abs(markup) < MAX_VALID_MARKUP) {
return true;
}
// 每周涨跌7%属于不正常
// 每周涨跌7%属于不正常
if (Math.abs(markup) > INVALID_MARKUP) {
return false;
}
if (avgMarkup < MIN_VALID_MARKUP) {
return false;
}
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
if (Math.abs(markup) > (avgMarkup + avgMarkup * MAX_AVG_MARKUP_FLOAT)) {
return false;
}
@@ -43,11 +43,11 @@ public class SellShopOfficeResultOperator implements Operator {
private OfficeStatDao officeStatDao = OfficeStatDao.getInstance();
private GuidingPriceDao guidingPriceDao = GuidingPriceDao.getInstance();
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MIN_VALID_MARKUP = 0.003d; // 每周最小有效涨跌幅0.3%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double MAX_VALID_MARKUP = 0.01d; // 每周最小有效涨跌幅1%
public static final double INVALID_MARKUP = 0.07d; // 每周最大有效涨跌幅7%
public static final double INVALID_MARKUP = 0.07d; // 每周最大有效涨跌幅7%
public static final int AVG_MARKUP_WEEKEND = 6;
@@ -93,16 +93,16 @@ public class SellShopOfficeResultOperator implements Operator {
if (lastRegionStat != null && lastRegionStat.getAvgPrice() > 0) {
double markup = (double) (value - lastRegionStat.getAvgPrice()) / (double) lastRegionStat.getAvgPrice();
// 最近4周的平均涨跌幅
// 最近4周的平均涨跌幅
avgMarkup = businessRegionStatDao.findLatestStatAvgMarkup(city, region, block, category, result.getCalcDate(), AVG_MARKUP_WEEKEND);
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
double realMarkup = balanceMarkup(markup, avgMarkup);
value = (int) (lastRegionStat.getAvgPrice() + lastRegionStat.getAvgPrice() * realMarkup);
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastRegionStat.getAvgPrice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -140,11 +140,11 @@ public class SellShopOfficeResultOperator implements Operator {
GuidingPrice guidingPrice = null;
Date startDate = DateUtil.add(DateUtil.formatByPattern(res.getCalcDate(), "yyyy-MM-dd"), -7);
if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
lastStat = shopStatDao.findShopStat(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), DateUtil.getLastSunday(res.getCalcDate()));
guidingPrice = guidingPriceDao.findFirstGuidingPrice(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), "shop_sell", startDate, res.getCalcDate());
stat = getAvgPrice(new ShopStat(), districtKey, res, lastStat);
//如果有指导价,优先使用指导价
//如果有指导价,优先使用指导价
if(guidingPrice!=null && guidingPrice.getGuidingValue()>0){
stat.setAvgPrice(guidingPrice.getGuidingValue());
if(lastStat != null){
@@ -153,7 +153,7 @@ public class SellShopOfficeResultOperator implements Operator {
}else{
stat.setWeekendMarkup(0);
}
stat.setSampleSize(1000);//如果有指导价,样本量人为设定
stat.setSampleSize(1000);//如果有指导价,样本量人为设定
}
@@ -161,11 +161,11 @@ public class SellShopOfficeResultOperator implements Operator {
shopStatDao.saveOrUpdateShopStat((ShopStat) stat);
checkUpdateHistoryPrice(stat, stat.getWeekend());
}
}else if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
}else if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
lastStat = officeStatDao.findOfficeStat(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), DateUtil.getLastSunday(res.getCalcDate()));
guidingPrice = guidingPriceDao.findFirstGuidingPrice(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), "office_sell", startDate, res.getCalcDate());
stat = getAvgPrice(new OfficeStat(), districtKey, res, lastStat);
//如果有指导价,优先使用指导价
//如果有指导价,优先使用指导价
if(guidingPrice!=null && guidingPrice.getGuidingValue()>0){
stat.setAvgPrice(guidingPrice.getGuidingValue());
if(lastStat != null){
@@ -174,7 +174,7 @@ public class SellShopOfficeResultOperator implements Operator {
}else{
stat.setWeekendMarkup(0);
}
stat.setSampleSize(1000);//如果有指导价,样本量人为设定
stat.setSampleSize(1000);//如果有指导价,样本量人为设定
}
if(stat.getAvgPrice() > 0){
@@ -218,7 +218,7 @@ public class SellShopOfficeResultOperator implements Operator {
}
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
// value为0,说明均价计算不出,所以拿前一期的均价进行随机涨跌
if (value == 0) {
value = lastStat.getAvgPrice();
}
@@ -226,16 +226,16 @@ public class SellShopOfficeResultOperator implements Operator {
double avgMarkup = 0;
if (lastStat != null && lastStat.getAvgPrice() > 0) {
double markup = (double) (value - lastStat.getAvgPrice()) / (double) lastStat.getAvgPrice();
// 最近6周的平均涨跌幅
// 最近6周的平均涨跌幅
if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
avgMarkup = shopStatDao.findLatestStatAvgMarkup(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), res.getCalcDate(), AVG_MARKUP_WEEKEND);
}else{
avgMarkup = officeStatDao.findLatestStatAvgMarkup(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), res.getCalcDate(), AVG_MARKUP_WEEKEND);
}
// 涨跌幅不正常
// 涨跌幅不正常
if (!isValidMarkup(markup, avgMarkup)) {
int level = checkHouseReliability(res.getSampleSize());
@@ -252,7 +252,7 @@ public class SellShopOfficeResultOperator implements Operator {
}
}
// 如果本周计算的均价与上周的相同
// 如果本周计算的均价与上周的相同
if (lastStat.getAvgPrice() == value) {
if (RandomUtil.nextBoolean()) {
value = (int) (value - value * (RandomUtil.random(3, 15) / 1000d));
@@ -283,9 +283,9 @@ public class SellShopOfficeResultOperator implements Operator {
private Integer getOtherWebsitePrice(DistrictKey districtKey){
AverageStatistics averageStatistics = null;
if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
averageStatistics = averageStatisticsDao.findLatestAverageStatistics(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), CategoryEnum.OFFICE.getCategory());
}else if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
}else if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
averageStatistics = averageStatisticsDao.findLatestAverageStatistics(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), CategoryEnum.SHOP.getCategory());
}
@@ -327,7 +327,7 @@ public class SellShopOfficeResultOperator implements Operator {
avgMarkup = MIN_VALID_MARKUP + ((double) RandomUtil.random(1, 20) / 10000d);
return avgMarkup;
} else {
// 大于平均涨跌幅的0.35倍,则使用平均涨跌幅控制
// 大于平均涨跌幅的0.35倍,则使用平均涨跌幅控制
int p = RandomUtil.random((int) (MIN_AVG_MARKUP_FLOAT * 100), (int) (MAX_AVG_MARKUP_FLOAT * 100));
ret = avgMarkup + avgMarkup * ((double) p / 100d);
if (markup < 0) {
@@ -339,25 +339,25 @@ public class SellShopOfficeResultOperator implements Operator {
}
/**
* 检查涨跌幅是否正常
* 检查涨跌幅是否正常
*
* @param markup
* @param avgMarkup
* @return
*/
private boolean isValidMarkup(double markup, double avgMarkup) {
// 每周涨跌1%属于正常
// 每周涨跌1%属于正常
if (Math.abs(markup) > MIN_VALID_MARKUP && Math.abs(markup) < MAX_VALID_MARKUP) {
return true;
}
// 每周涨跌7%属于不正常
// 每周涨跌7%属于不正常
if (Math.abs(markup) > INVALID_MARKUP) {
return false;
}
if (avgMarkup < MIN_VALID_MARKUP) {
return false;
}
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
// 大于平均涨跌幅的0.35倍属于不正常,这样会造成曲线波动很大
if (Math.abs(markup) > (avgMarkup + avgMarkup * MAX_AVG_MARKUP_FLOAT)) {
return false;
}
@@ -368,9 +368,9 @@ public class SellShopOfficeResultOperator implements Operator {
private Stat getMaxHouseCountStat(Stat stat, Date claDate){
Stat maxStat = null;
if(stat.getEstateType().equals("商铺")){
if(stat.getEstateType().equals("商铺")){
maxStat = shopStatDao.findShopStatMaxHouseCount(stat.getCity(), stat.getRegion(), stat.getDistrictName(),claDate);
}else if(stat.getEstateType().equals("写字楼")){
}else if(stat.getEstateType().equals("写字楼")){
maxStat = officeStatDao.findOfficeStatMaxHouseCount(stat.getCity(), stat.getRegion(), stat.getDistrictName(),claDate);
}
@@ -385,9 +385,9 @@ public class SellShopOfficeResultOperator implements Operator {
private Stat getMaxOrMinStat(Stat stat, Date claDate, boolean isAsc){
Stat tempStat = null;
if(stat.getEstateType().equals("商铺")){
if(stat.getEstateType().equals("商铺")){
tempStat = shopStatDao.findShopStatMinPrice(stat.getCity(), stat.getRegion(), stat.getDistrictName(),claDate, isAsc);
}else if(stat.getEstateType().equals("写字楼")){
}else if(stat.getEstateType().equals("写字楼")){
tempStat = officeStatDao.findOfficeStatMinPrice(stat.getCity(), stat.getRegion(), stat.getDistrictName(),claDate, isAsc);
}
return tempStat;
@@ -395,9 +395,9 @@ public class SellShopOfficeResultOperator implements Operator {
private Date getFirstWeekendFromHistory(Stat stat, Date claDate){
Date firstDate = null;
if(stat.getEstateType().equals("商铺")){
if(stat.getEstateType().equals("商铺")){
firstDate = shopStatDao.findShopStatFirstWeekend(stat.getCity(), stat.getRegion(), stat.getDistrictName());
}else if(stat.getEstateType().equals("写字楼")){
}else if(stat.getEstateType().equals("写字楼")){
firstDate = officeStatDao.findOfficeStatFirstWeekend(stat.getCity(), stat.getRegion(), stat.getDistrictName());
}
return firstDate;
@@ -406,18 +406,18 @@ public class SellShopOfficeResultOperator implements Operator {
private Map<String, Integer> getAllHistoryStat(Stat stat, Date claDate){
Map<String, Integer> rentMap = null;
if(stat.getEstateType().equals("商铺")){
if(stat.getEstateType().equals("商铺")){
rentMap = shopStatDao.findAllHistoryPrice(stat.getCity(), stat.getRegion(), stat.getDistrictName(), claDate);
}else if(stat.getEstateType().equals("写字楼")){
}else if(stat.getEstateType().equals("写字楼")){
rentMap = officeStatDao.findAllHistoryPrice(stat.getCity(), stat.getRegion(), stat.getDistrictName(), claDate);
}
return rentMap;
}
private void updateStat(String city,String region, String name, int price, int markup, Date calDate, String type){
if(type.equals("商铺")){
if(type.equals("商铺")){
shopStatDao.update(city, region, name, price, markup, calDate);
}else if(type.equals("写字楼")){
}else if(type.equals("写字楼")){
officeStatDao.update(city, region, name, price, markup, calDate);
}
@@ -486,7 +486,7 @@ public class SellShopOfficeResultOperator implements Operator {
}
if(Math.abs(tempMarkup)>3){
// 随机[-0.5~1.5)的涨跌幅
// 随机[-0.5~1.5)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * -1+0.5);
double markup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
@@ -510,7 +510,7 @@ public class SellShopOfficeResultOperator implements Operator {
}
if(Math.abs(tempMarkup)>3){
// 随机[0~2)的涨跌幅
// 随机[0~2)的涨跌幅
BigDecimal bg = new BigDecimal(Math.random() * 2);
double markup = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
int avg_price = (int) (newPrices.get(j-1) * (1 + markup / 100));
@@ -524,9 +524,9 @@ public class SellShopOfficeResultOperator implements Operator {
}
//更新价格
//更新价格
if(isUpdate){
System.out.println(" 修正后: " +newPrices.toString());
System.out.println(" 修正后: " +newPrices.toString());
for(int m = 0;m < weekends.size(); m++){
String weekend = weekends.get(m);
Integer newPrice = newPrices.get(m);
@@ -62,7 +62,7 @@ public abstract class AbstractProvider implements Provider {
List<Data> dataList = new ArrayList<Data>();
// 如果是县级市,则不考虑区域
// 如果是县级市,则不考虑区域
if (serverAreaDao.isCountyLevelCity(city)) {
for (String districtName : aliasNames) {
dataList.addAll(dataHolder.getDistrictData(null, districtName));
@@ -168,7 +168,7 @@ public abstract class AbstractProvider implements Provider {
List<Data> dataList = new ArrayList<Data>();
// 如果是县级市,则不考虑区域
// 如果是县级市,则不考虑区域
if (serverAreaDao.isCountyLevelCity(city)) {
for (String districtName : aliasNames) {
dataList.addAll(dataHolder.getDistrictHouseData(city, null, districtName, startDate, null));
@@ -231,7 +231,7 @@ public abstract class AbstractProvider implements Provider {
List<Data> dataList = new ArrayList<Data>();
// 如果是县级市,则不考虑区域
// 如果是县级市,则不考虑区域
if (serverAreaDao.isCountyLevelCity(city)) {
for (String districtName : aliasNames) {
dataList.addAll(dataHolder.getDistrictHouseData(districtKey.getCity(), null, districtName, startDate, endDate));
@@ -299,7 +299,7 @@ public abstract class AbstractProvider implements Provider {
List<Data> dataList = new ArrayList<Data>();
// 如果是县级市,则不考虑区域
// 如果是县级市,则不考虑区域
if (serverAreaDao.isCountyLevelCity(city)) {
//for (String districtName : aliasNames) {
dataList.addAll(dataHolder.getDistrictHouseData2(districtKey.getCity(), null, new ArrayList<String>(aliasNames), startDate, endDate));
@@ -126,9 +126,9 @@ public class RentHouseDataProvider extends AbstractProvider{
if(district.getRegion().equals(dist.getRegion()) && district.getName().equals(dist.getName())){
continue;
}
String estateType = "小区";
if(district.getEstateType2()!=null && district.getEstateType2().equals("别墅")){
estateType = "别墅";
String estateType = "小区";
if(district.getEstateType2()!=null && district.getEstateType2().equals("别墅")){
estateType = "别墅";
}
if(!districtKey.getEstateTypeEnum().getEstateType().equals(estateType)){
continue;
@@ -264,9 +264,9 @@ public class RentHouseDataProvider extends AbstractProvider{
if(district.getRegion().equals(dist.getRegion()) && district.getName().equals(dist.getName())){
continue;
}
String estateType = "小区";
if(district.getEstateType2()!=null && district.getEstateType2().equals("别墅")){
estateType = "别墅";
String estateType = "小区";
if(district.getEstateType2()!=null && district.getEstateType2().equals("别墅")){
estateType = "别墅";
}
if(!districtKey.getEstateTypeEnum().getEstateType().equals(estateType)){
continue;
@@ -333,7 +333,7 @@ public class RentHouseDataProvider extends AbstractProvider{
Date endDate, Integer radio, Integer minRadio) {
List<District> districts = fetchArroundDistrictsByDistance(districtKey, radio, minRadio);
System.out.println("周边小区数:"+districts.size() +" 范围:"+radio);
System.out.println("周边小区数:"+districts.size() +" 范围:"+radio);
if(districts.size() > 0){
List<Double> allDatas = new ArrayList<Double>();
for(District district : districts){
@@ -488,7 +488,7 @@ public class RentHouseDataProvider extends AbstractProvider{
public List<Double> fetchAroundHouseData(DistrictKey districtKey,
Date startDate, Date endDate, Integer radio, Integer minRadio) {
List<District> districts = fetchArroundDistrictsByDistance(districtKey, radio, minRadio);
System.out.println("周边小区数:"+districts.size() +" 范围:"+radio);
System.out.println("周边小区数:"+districts.size() +" 范围:"+radio);
if(districts.size() > 0){
List<Double> allDatas = new ArrayList<Double>();
for(District district : districts){
@@ -45,13 +45,13 @@ public class SellHouseDataProvider extends AbstractProvider {
List<Data> ret = new ArrayList<Data>();
if (districtMap != null) {
// 每个小区最大的样本数量
// 每个小区最大的样本数量
for (DistrictKey key : districtMap.keySet()) {
District district = districtMap.get(key);
List<Data> datas = getData(new DistrictKey(district.getCity(), district.getRegion(), district.getName(),
CategoryEnum.DISTRICT, EstateTypeEnum.DISTRICT));
for (int i = 0; i < datas.size() && i <= DISTRICT_SAMPLE_SIZE; i++) {
// 别墅不参与城市均价计算
// 别墅不参与城市均价计算
if (!datas.get(i).isVilla()) {
ret.add(datas.get(i));
}
@@ -84,13 +84,13 @@ public class SellShopOfficeDataProvider extends AbstractProvider {
if(district.getRegion().equals(districtKey.getRegion()) && district.getName().equals(districtKey.getName())){
continue;
}
if(districtKey.getCategoryEnum().getDisplay().equals("ÉÌÆÌ")){
if(districtKey.getCategoryEnum().getDisplay().equals("商铺")){
ShopStat lastStat = shopStatDao.findNearShopStat(district.getCity(), district.getRegion(),
district.getName(), calcDate);
if(lastStat!=null && lastStat.getAvgPrice()>0){
points.add(lastStat.getAvgPrice());
}
}else if(districtKey.getCategoryEnum().getDisplay().equals("д×ÖÂ¥")){
}else if(districtKey.getCategoryEnum().getDisplay().equals("写字楼")){
OfficeStat lastStat = officeStatDao.findNearOfficeStat(district.getCity(), district.getRegion(),
district.getName(), calcDate);
if(lastStat!=null && lastStat.getAvgPrice()>0){
@@ -1,11 +1,11 @@
package com.fangjia.coredata.price.tree;
public class Data implements Cloneable {
private boolean villa; // 是否是别墅
private int val; // 价格
private int date; // 日期
private boolean isClone; // 是否是复制的
private int room;//室
private boolean villa; // 是否是别墅
private int val; // 价格
private int date; // 日期
private boolean isClone; // 是否是复制的
private int room;//室
private double area;
public Data(int val, int date, boolean villa, int room, double area) {
@@ -33,7 +33,7 @@ import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* 数据树
* 数据树
*
* @author xiaoyu
*
@@ -143,7 +143,7 @@ public class DataHolder {
}
/**
* 获取小区数据 结果按时间倒序排列
* 获取小区数据 结果按时间倒序排列
*
* @param regionName
* @param districtName
@@ -246,7 +246,7 @@ public class DataHolder {
if(!keys.contains(key)){
keys.add(key);
if(StringUtils.isNotBlank(house.getFitment())){
String[] typeWords = {"毛坯", "清水", "无装修", "独栋毛坯"};
String[] typeWords = {"毛坯", "清水", "无装修", "独栋毛坯"};
if(StringUtils.indexOfAny(house.getFitment(), typeWords)>-1){
house.setTotalPrice((int)(house.getTotalPrice()/0.6));
}
@@ -301,7 +301,7 @@ public class DataHolder {
if(!keys.contains(key)){
keys.add(key);
if(StringUtils.isNotBlank(house.getFitment())){
String[] typeWords = {"毛坯", "清水", "无装修", "独栋毛坯"};
String[] typeWords = {"毛坯", "清水", "无装修", "独栋毛坯"};
if(StringUtils.indexOfAny(house.getFitment(), typeWords)>-1){
house.setTotalPrice((int)(house.getTotalPrice()/0.6));
}
@@ -576,7 +576,7 @@ public List<Data> getDistrictHouseData(String regionName, String districtName, D
}
/**
* 需要删除的时间
* 需要删除的时间
*
* @param orgStart
* @param orgEnd
@@ -611,7 +611,7 @@ public List<Data> getDistrictHouseData(String regionName, String districtName, D
}
/**
* 需要补充的时间
* 需要补充的时间
*
* @param orgStart
* @param orgEnd
@@ -1,7 +1,7 @@
package com.fangjia.coredata.price.util;
/**
* 异步运行线程
* 异步运行线程
*
* @author xiaoyu
*
@@ -10,15 +10,15 @@ import com.fangjia.coredata.price.core.Cluster;
public class DataCluster {
// 聚类桶宽百分比
// 聚类桶宽百分比
public static final int CLUSTER_PERCENT = 5;
// 聚类中最小的成员数
// 聚类中最小的成员数
public static final int MIN_SUPPORT_COUNT = 3;
// 聚类中最大值与最小值的比差
// 聚类中最大值与最小值的比差
public static final double HIGH_DIFFERENCE_PERCENT = 1.2;
// 小区聚类的最小聚类簇个数
// 小区聚类的最小聚类簇个数
public static final int MIN_CLUSTER_COUNT = 1;
// 区域聚类的聚类簇个数
// 区域聚类的聚类簇个数
public static final int REGION_CLUSTER_SIZE = 3;
public static final double MIN_EXTREME_VALUE_PERCENT = 0.2d;
@@ -30,7 +30,7 @@ public class DataCluster {
}
/**
* 开始执行聚类算法
* 开始执行聚类算法
*
* @param values
* @return List<Cluster>
@@ -38,7 +38,7 @@ public class DataCluster {
public static Cluster cluster(List<Integer> values) {
if (values != null && values.size() > MIN_SUPPORT_COUNT) {
Collections.sort(values);
// 去除20%最小值,3%最大值,使均值整体朝大的一端偏移
// 去除20%最小值,3%最大值,使均值整体朝大的一端偏移
int l = (int) Math.ceil(values.size() * MIN_EXTREME_VALUE_PERCENT);
int h = (int) Math.ceil(values.size() * (1 - MAX_EXTREME_VALUE_PERCENT));
if (values.size() / 10 > 1) {
@@ -88,16 +88,16 @@ public class DataCluster {
/**
*
* @param allAvgs
* 数值列表
* 数值列表
* @param minCluster
* 最少聚出的类个数
* 最少聚出的类个数
* @param percent
* 聚类间距
* 聚类间距
* @param minSize
* 聚类中最小的成员数
* 聚类中最小的成员数
* @param heightDifferencePercent
* 如果聚类中最大值与最小值的比差,只在聚出一个类,并且最小聚类大于一的情况下使用
* @return 聚类列表
* 如果聚类中最大值与最小值的比差,只在聚出一个类,并且最小聚类大于一的情况下使用
* @return 聚类列表
*/
private static double[][] cluster(List<Integer> allAvgs, int minCluster, int percent, int minSize,
double heightDifferencePercent) {
@@ -121,13 +121,13 @@ public class DataCluster {
allClusterSep += allAvgs.get(i);
}
int clusterSep = NumberUtils.round(allClusterSep * percent * 1.0d / (100 * (allAvgs.size() - startfrom)));// 平均数量大小,总值
compStep = NumberUtils.round(clusterSep * 0.5);// 增量
int clusterSep = NumberUtils.round(allClusterSep * percent * 1.0d / (100 * (allAvgs.size() - startfrom)));// 平均数量大小,总值
compStep = NumberUtils.round(clusterSep * 0.5);// 增量
if(compStep == 0){
compStep = 1;
}
compAvg = allAvgs.get(startfrom) + compStep;// 初始均价大小
startfrom_temp = startfrom;// 起始点
compAvg = allAvgs.get(startfrom) + compStep;// 初始均价大小
startfrom_temp = startfrom;// 起始点
ArrayList<int[]> clusters = new ArrayList<int[]>();
ArrayList<int[]> historyClusters = new ArrayList<int[]>();
@@ -152,14 +152,14 @@ public class DataCluster {
}
if (end - start + 1 >= minSize) {
historyClusters.add(new int[] { start, end });
if (clusters.isEmpty()) {// 新加组
if (clusters.isEmpty()) {// 新加组
clusters.add(new int[] { start, end });
} else {
int[] before = clusters.get(clusters.size() - 1);
if (start <= before[1]) {// 合并
if (start <= before[1]) {// 合并
before[1] = end;
} else {// 新加组
} else {// 新加组
clusters.add(new int[] { start, end });
}
}
@@ -224,7 +224,7 @@ public class DataCluster {
}
/**
* 对大簇进行划分
* 对大簇进行划分
*
* @param cluster
* @param minCluster
@@ -244,7 +244,7 @@ public class DataCluster {
int clusterLength = cluster.length;
int compStep = NumberUtils.round(clusterSep * 0.5);// 增量
int compStep = NumberUtils.round(clusterSep * 0.5);// 增量
int compAvg = allAvgs.get(cluster[0]) + compStep;
while (compAvg <= allAvgs.get(cluster[clusterLength - 1])) {
@@ -290,7 +290,7 @@ public class DataCluster {
int bs = b[1] - b[0];
int cs = c[1] - c[0];
if (bs > as && bs > cs) {// 波峰
if (bs > as && bs > cs) {// 波峰
int avg = 0;
for (int k = b[0]; k <= b[1]; k++) {
avg += allAvgs.get(k);
@@ -300,17 +300,17 @@ public class DataCluster {
topWaveMarkCount++;
flag = 0;
} else if (bs < as && bs < cs) {// 波谷
} else if (bs < as && bs < cs) {// 波谷
waveMark.add(new int[] { i * -1, 0 });
bottomWaveMarkCount++;
flag = 0;
} else if (bs > as && bs == cs) {// 波峰开始
} else if (bs > as && bs == cs) {// 波峰开始
flag = 1;
} else if (bs < as && bs == cs) {// 波谷开始
} else if (bs < as && bs == cs) {// 波谷开始
flag = -1;
} else if (flag == 1 && (bs == as && bs > cs)) {// 波峰
// 下降通道
} else if (flag == 1 && (bs == as && bs > cs)) {// 波峰
// 下降通道
int avg = 0;
for (int k = b[0]; k <= b[1]; k++) {
avg += allAvgs.get(k);
@@ -320,13 +320,13 @@ public class DataCluster {
topWaveMarkCount++;
flag = 0;
} else if (flag == -1 && (bs == as && bs < cs)) {// 波谷
// 上升通道
} else if (flag == -1 && (bs == as && bs < cs)) {// 波谷
// 上升通道
waveMark.add(new int[] { i * -1, 0 });
bottomWaveMarkCount++;
flag = 0;
} else if (bs == as && bs == cs) {// 平滑区
} else if (bs == as && bs == cs) {// 平滑区
} else {
flag = 0;
@@ -336,11 +336,11 @@ public class DataCluster {
List<Integer> bottomMark = new ArrayList<Integer>();
// 取出(minCluster-1)个波谷,断裂
// 取出(minCluster-1)个波谷,断裂
if (bottomWaveMarkCount > 0) {
clusters.clear();
if (topWaveMarkCount > minCluster) {// 按波峰之间的距离选取聚类
if (topWaveMarkCount > minCluster) {// 按波峰之间的距离选取聚类
int startIndex = 2;
@@ -352,12 +352,12 @@ public class DataCluster {
int count = 0;
for (int i = startIndex; i < waveMark.size(); i += 2) {
x[count][0] = waveMark.get(i)[1] - waveMark.get(i - 2)[1]; // 均价间距
x[count][1] = i - 1; // 记录波谷位置
x[count][0] = waveMark.get(i)[1] - waveMark.get(i - 2)[1]; // 均价间距
x[count][1] = i - 1; // 记录波谷位置
count++;
}
// 按间距排序
// 按间距排序
Arrays.sort(x, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
@@ -384,14 +384,14 @@ public class DataCluster {
Collections.sort(bottomMark);
// 合并
// 合并
int lastIndex = 0;
for (int i = 0; i <= bottomMark.size(); i++) {
int start = Integer.MAX_VALUE;
int end = 0;
// 求峰值的平均值,往两边扩散
// 求峰值的平均值,往两边扩散
int bottomIndex = 0;
if (i == bottomMark.size())
bottomIndex = waveMark.size();
@@ -10,15 +10,15 @@ import com.fangjia.coredata.price.core.Cluster;
public class DataCluster2 {
// 聚类桶宽百分比
// 聚类桶宽百分比
public static final int CLUSTER_PERCENT = 5;
// 聚类中最小的成员数
// 聚类中最小的成员数
public static final int MIN_SUPPORT_COUNT = 3;
// 聚类中最大值与最小值的比差
// 聚类中最大值与最小值的比差
public static final double HIGH_DIFFERENCE_PERCENT = 1.2;
// 小区聚类的最小聚类簇个数
// 小区聚类的最小聚类簇个数
public static final int MIN_CLUSTER_COUNT = 1;
// 区域聚类的聚类簇个数
// 区域聚类的聚类簇个数
public static final int REGION_CLUSTER_SIZE = 3;
public static final double MIN_EXTREME_VALUE_PERCENT = 0.2d;
@@ -30,7 +30,7 @@ public class DataCluster2 {
}
/**
* 开始执行聚类算法
* 开始执行聚类算法
*
* @param values
* @return List<Cluster>
@@ -38,7 +38,7 @@ public class DataCluster2 {
public static Cluster cluster(List<Double> values) {
if (values != null && values.size() > MIN_SUPPORT_COUNT) {
Collections.sort(values);
// 去除20%最小值,3%最大值,使均值整体朝大的一端偏移
// 去除20%最小值,3%最大值,使均值整体朝大的一端偏移
int l = (int) Math.ceil(values.size() * MIN_EXTREME_VALUE_PERCENT);
int h = (int) Math.ceil(values.size() * (1 - MAX_EXTREME_VALUE_PERCENT));
if (values.size() / 10 > 1) {
@@ -88,16 +88,16 @@ public class DataCluster2 {
/**
*
* @param allAvgs
* 数值列表
* 数值列表
* @param minCluster
* 最少聚出的类个数
* 最少聚出的类个数
* @param percent
* 聚类间距
* 聚类间距
* @param minSize
* 聚类中最小的成员数
* 聚类中最小的成员数
* @param heightDifferencePercent
* 如果聚类中最大值与最小值的比差,只在聚出一个类,并且最小聚类大于一的情况下使用
* @return 聚类列表
* 如果聚类中最大值与最小值的比差,只在聚出一个类,并且最小聚类大于一的情况下使用
* @return 聚类列表
*/
private static double[][] cluster(List<Double> allAvgs, int minCluster, int percent, int minSize,
double heightDifferencePercent) {
@@ -121,13 +121,13 @@ public class DataCluster2 {
allClusterSep += allAvgs.get(i);
}
int clusterSep = NumberUtils.round(allClusterSep * percent * 1.0d / (100 * (allAvgs.size() - startfrom)));// 平均数量大小,总值
compStep = NumberUtils.round(clusterSep * 0.5);// 增量
int clusterSep = NumberUtils.round(allClusterSep * percent * 1.0d / (100 * (allAvgs.size() - startfrom)));// 平均数量大小,总值
compStep = NumberUtils.round(clusterSep * 0.5);// 增量
if(compStep == 0){
compStep = 1;
}
compAvg = allAvgs.get(startfrom) + compStep;// 初始均价大小
startfrom_temp = startfrom;// 起始点
compAvg = allAvgs.get(startfrom) + compStep;// 初始均价大小
startfrom_temp = startfrom;// 起始点
ArrayList<int[]> clusters = new ArrayList<int[]>();
ArrayList<int[]> historyClusters = new ArrayList<int[]>();
@@ -152,14 +152,14 @@ public class DataCluster2 {
}
if (end - start + 1 >= minSize) {
historyClusters.add(new int[] { start, end });
if (clusters.isEmpty()) {// 新加组
if (clusters.isEmpty()) {// 新加组
clusters.add(new int[] { start, end });
} else {
int[] before = clusters.get(clusters.size() - 1);
if (start <= before[1]) {// 合并
if (start <= before[1]) {// 合并
before[1] = end;
} else {// 新加组
} else {// 新加组
clusters.add(new int[] { start, end });
}
}
@@ -224,7 +224,7 @@ public class DataCluster2 {
}
/**
* 对大簇进行划分
* 对大簇进行划分
*
* @param cluster
* @param minCluster
@@ -244,7 +244,7 @@ public class DataCluster2 {
int clusterLength = cluster.length;
int compStep = NumberUtils.round(clusterSep * 0.5);// 增量
int compStep = NumberUtils.round(clusterSep * 0.5);// 增量
double compAvg = allAvgs.get(cluster[0]) + compStep;
while (compAvg <= allAvgs.get(cluster[clusterLength - 1])) {
@@ -290,7 +290,7 @@ public class DataCluster2 {
int bs = b[1] - b[0];
int cs = c[1] - c[0];
if (bs > as && bs > cs) {// 波峰
if (bs > as && bs > cs) {// 波峰
int avg = 0;
for (int k = b[0]; k <= b[1]; k++) {
avg += allAvgs.get(k);
@@ -300,17 +300,17 @@ public class DataCluster2 {
topWaveMarkCount++;
flag = 0;
} else if (bs < as && bs < cs) {// 波谷
} else if (bs < as && bs < cs) {// 波谷
waveMark.add(new int[] { i * -1, 0 });
bottomWaveMarkCount++;
flag = 0;
} else if (bs > as && bs == cs) {// 波峰开始
} else if (bs > as && bs == cs) {// 波峰开始
flag = 1;
} else if (bs < as && bs == cs) {// 波谷开始
} else if (bs < as && bs == cs) {// 波谷开始
flag = -1;
} else if (flag == 1 && (bs == as && bs > cs)) {// 波峰
// 下降通道
} else if (flag == 1 && (bs == as && bs > cs)) {// 波峰
// 下降通道
int avg = 0;
for (int k = b[0]; k <= b[1]; k++) {
avg += allAvgs.get(k);
@@ -320,13 +320,13 @@ public class DataCluster2 {
topWaveMarkCount++;
flag = 0;
} else if (flag == -1 && (bs == as && bs < cs)) {// 波谷
// 上升通道
} else if (flag == -1 && (bs == as && bs < cs)) {// 波谷
// 上升通道
waveMark.add(new int[] { i * -1, 0 });
bottomWaveMarkCount++;
flag = 0;
} else if (bs == as && bs == cs) {// 平滑区
} else if (bs == as && bs == cs) {// 平滑区
} else {
flag = 0;
@@ -336,11 +336,11 @@ public class DataCluster2 {
List<Integer> bottomMark = new ArrayList<Integer>();
// 取出(minCluster-1)个波谷,断裂
// 取出(minCluster-1)个波谷,断裂
if (bottomWaveMarkCount > 0) {
clusters.clear();
if (topWaveMarkCount > minCluster) {// 按波峰之间的距离选取聚类
if (topWaveMarkCount > minCluster) {// 按波峰之间的距离选取聚类
int startIndex = 2;
@@ -352,12 +352,12 @@ public class DataCluster2 {
int count = 0;
for (int i = startIndex; i < waveMark.size(); i += 2) {
x[count][0] = waveMark.get(i)[1] - waveMark.get(i - 2)[1]; // 均价间距
x[count][1] = i - 1; // 记录波谷位置
x[count][0] = waveMark.get(i)[1] - waveMark.get(i - 2)[1]; // 均价间距
x[count][1] = i - 1; // 记录波谷位置
count++;
}
// 按间距排序
// 按间距排序
Arrays.sort(x, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
@@ -384,14 +384,14 @@ public class DataCluster2 {
Collections.sort(bottomMark);
// 合并
// 合并
int lastIndex = 0;
for (int i = 0; i <= bottomMark.size(); i++) {
int start = Integer.MAX_VALUE;
int end = 0;
// 求峰值的平均值,往两边扩散
// 求峰值的平均值,往两边扩散
int bottomIndex = 0;
if (i == bottomMark.size())
bottomIndex = waveMark.size();
@@ -6,7 +6,7 @@ import java.util.List;
import java.util.Map;
public class ServiceUtils {
//获取完整的房型
//获取完整的房型
public static List<Integer> getAllRooms(List<Integer> rooms){
Collections.sort(rooms);
int start = rooms.get(0);
@@ -63,105 +63,105 @@ public class DataCluster3 {
}
/*
* 聚类函数主体。 针对一维 double 数组。指定聚类数目 k。 将数据聚成 k 类。
* 聚类函数主体。 针对一维 double 数组。指定聚类数目 k。 将数据聚成 k 类。
*/
private static double[][] cluster(double[] p, int k) {
// 存放聚类旧的聚类中心
// 存放聚类旧的聚类中心
double[] c = new double[k];
// 存放新计算的聚类中心
// 存放新计算的聚类中心
double[] nc = new double[k];
// 存放放回结果
// 存放放回结果
double[][] ret;
// 初始化聚类中心
// 经典方法是随机选取 k 个
// 本例中采用前 k 个作为聚类中心
// 聚类中心的选取不影响最终结果
// 初始化聚类中心
// 经典方法是随机选取 k 个
// 本例中采用前 k 个作为聚类中心
// 聚类中心的选取不影响最终结果
for (int i = 0; i < k; i++)
c[i] = p[i];
// 循环聚类,更新聚类中心
// 到聚类中心不变为止
// 循环聚类,更新聚类中心
// 到聚类中心不变为止
while (true) {
// 根据聚类中心将元素分类
// 根据聚类中心将元素分类
ret = group(p, c);
// 计算分类后的聚类中心
// 计算分类后的聚类中心
for (int i = 0; i < ret.length; i++) {
if (ret[i].length > 0) {
nc[i] = center(ret[i]);
}
}
// 如果聚类中心不同
// 如果聚类中心不同
if (!equal(nc, c)) {
// 为下一次聚类准备
// 为下一次聚类准备
c = nc;
nc = new double[k];
} else
// 聚类结束
// 聚类结束
break;
}
// 返回聚类结果
// 返回聚类结果
return ret;
}
/*
* 聚类中心函数 简单的一维聚类返回其算数平均值 可扩展
* 聚类中心函数 简单的一维聚类返回其算数平均值 可扩展
*/
private static double center(double[] p) {
return sum(p) / p.length;
}
/*
* 给定 double 型数组 p 和聚类中心 c。 根据 c 将 p 中元素聚类。返回二维数组。 存放各组元素。
* 给定 double 型数组 p 和聚类中心 c。 根据 c 将 p 中元素聚类。返回二维数组。 存放各组元素。
*/
private static double[][] group(double[] p, double[] c) {
// 中间变量,用来分组标记
// 中间变量,用来分组标记
int[] gi = new int[p.length];
// 考察每一个元素 pi 同聚类中心 cj 的距离
// pi 与 cj 的距离最小则归为 j 类
// 考察每一个元素 pi 同聚类中心 cj 的距离
// pi 与 cj 的距离最小则归为 j 类
for (int i = 0; i < p.length; i++) {
// 存放距离
// 存放距离
double[] d = new double[c.length];
// 计算到每个聚类中心的距离
// 计算到每个聚类中心的距离
for (int j = 0; j < c.length; j++) {
d[j] = distance(p[i], c[j]);
}
// 找出最小距离,返回最小值的下标
// 找出最小距离,返回最小值的下标
int ci = min(d);
// 标记属于哪一组
// 标记属于哪一组
gi[i] = ci;
}
// 存放分组结果
// 存放分组结果
double[][] g = new double[c.length][];
// 遍历每个聚类中心,分组
// 遍历每个聚类中心,分组
for (int i = 0; i < c.length; i++) {
// 中间变量,记录聚类后每一组的大小
// 中间变量,记录聚类后每一组的大小
int s = 0;
// 计算每一组的长度
// 计算每一组的长度
for (int j = 0; j < gi.length; j++)
if (gi[j] == i)
s++;
// 存储每一组的成员
// 存储每一组的成员
g[i] = new double[s];
s = 0;
// 根据分组标记将各元素归位
// 根据分组标记将各元素归位
for (int j = 0; j < gi.length; j++)
if (gi[j] == i) {
g[i][s] = p[j];
s++;
}
}
// 返回分组结果
// 返回分组结果
return g;
}
/*
* 计算两个点之间的距离, 这里采用最简单得一维欧氏距离, 可扩展。
* 计算两个点之间的距离, 这里采用最简单得一维欧氏距离, 可扩展。
*/
private static double distance(double x, double y) {
return Math.abs(x - y);
}
/*
* 返回给定 double 数组各元素之和。
* 返回给定 double 数组各元素之和。
*/
private static double sum(double[] p) {
double sum = 0.0;
@@ -171,7 +171,7 @@ public class DataCluster3 {
}
/*
* 给定 double 类型数组,返回最小值得下标。
* 给定 double 类型数组,返回最小值得下标。
*/
private static int min(double[] p) {
int i = 0;
@@ -186,7 +186,7 @@ public class DataCluster3 {
}
/*
* 判断两个 double 数组是否相等。 长度一样且对应位置值相同返回真。
* 判断两个 double 数组是否相等。 长度一样且对应位置值相同返回真。
*/
private static boolean equal(double[] a, double[] b) {
if (a.length != b.length)
@@ -8,7 +8,7 @@ public class DistrictCommandMessageSender {
// private static CommandMessageDao commandMessageDao = CommandMessageDao.getInstance();
//
// public static void main(String[] args) {
// calculatorDistrictWeeklyAveragePrice("上海", DateUtil.getThisSunday(new Date()), OperateEnum.CALC);
// calculatorDistrictWeeklyAveragePrice("上海", DateUtil.getThisSunday(new Date()), OperateEnum.CALC);
// calculatorCityWeeklyAverage(DateUtil.getThisSunday(new Date()), OperateEnum.CALC);
// }
//
@@ -1,7 +1,7 @@
package com.fangjia.coredata.price.ztest;
/**
* 最小二乘法 线性回归
* 最小二乘法 线性回归
*
* @author xiaoyu
*
@@ -15,7 +15,7 @@ public class LineCoefficient {
}
/**
* 预测
* 预测
*
* @param x
* @param y
@@ -29,7 +29,7 @@ public class LineCoefficient {
}
/**
* 计算 x 的系数
* 计算 x 的系数
*
* @param x
* @param y
@@ -41,7 +41,7 @@ public class LineCoefficient {
}
/**
* 计算常量系数
* 计算常量系数
*
* @param x
* @param y
@@ -54,7 +54,7 @@ public class LineCoefficient {
}
/**
* 计算常量系数
* 计算常量系数
*
* @param x
* @param y
@@ -4,15 +4,15 @@ import java.util.ArrayList;
import java.util.List;
public class Node {
private String nodeName; // 样本点名
private double[] dimensioin; // 样本点的维度
private double kDistance; // k-距离
private List<Node> kNeighbor = new ArrayList<Node>();// k-领域
private double distance; // 到给定点的欧几里得距离
private double reachDensity;// 可达密度
private double reachDis;// 可达距离
private String nodeName; // 样本点名
private double[] dimensioin; // 样本点的维度
private double kDistance; // k-距离
private List<Node> kNeighbor = new ArrayList<Node>();// k-领域
private double distance; // 到给定点的欧几里得距离
private double reachDensity;// 可达密度
private double reachDis;// 可达距离
private double lof;// 局部离群因子
private double lof;// 局部离群因子
public Node() {
@@ -8,11 +8,11 @@ import java.util.List;
public class OutlierNodeDetect {
private static int MIN_PTS = 5;
// 1.找到给定点与其他点的欧几里得距离
// 2.对欧几里得距离进行排序,找到前5位的点,并同时记下k距离
// 3.计算每个点的可达密度
// 4.计算每个点的局部离群点因子
// 5.对每个点的局部离群点因子进行排序,输出。
// 1.找到给定点与其他点的欧几里得距离
// 2.对欧几里得距离进行排序,找到前5位的点,并同时记下k距离
// 3.计算每个点的可达密度
// 4.计算每个点的局部离群点因子
// 5.对每个点的局部离群点因子进行排序,输出。
public List<Node> getOutlierNode(List<Node> allNodes) {
List<Node> kdAndKnList = getKDAndKN(allNodes);
@@ -100,7 +100,7 @@ public class OutlierNodeDetect {
tempNodeList.add(nodeB);
}
// 对tempNodeList进行排序
// 对tempNodeList进行排序
Collections.sort(tempNodeList, new DistComparator());
for (int k = 1; k < MIN_PTS; k++) {
nodeA.getkNeighbor().add(tempNodeList.get(k));
@@ -156,7 +156,7 @@ public class OutlierNodeDetect {
double[] j = { 1, 6 };
double[] k = { 1, 5 };
double[] l = { 1, 2 };// 孤立点
double[] l = { 1, 2 };// 孤立点
double[] m = { 1, 20 };
double[] n = { 1, 19 };
@@ -17,51 +17,51 @@ import java.util.regex.Pattern;
public class AddressParser {
static Pattern regExp_checkRoad1=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)$");
static Pattern regExp_checkRoad2=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04$");
static Pattern regExp_checkRoad3=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7?\\-[0-9]+\u53F7$");
static Pattern regExp_checkRoad4=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7?\\-[0-9]+\u53F7$");
static Pattern regExp_checkRoad5=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+$");
static Pattern regExp_checkRoad6=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7$");
static Pattern regExp_checkRoad7=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7$");
static Pattern regExp_checkRoad8=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?\\-[0-9]+(\u5F04|\u53F7)$");
static Pattern regExp_checkRoad1=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)$");
static Pattern regExp_checkRoad2=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04$");
static Pattern regExp_checkRoad3=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7?\\-[0-9]+\u53F7$");
static Pattern regExp_checkRoad4=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7?\\-[0-9]+\u53F7$");
static Pattern regExp_checkRoad5=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+$");
static Pattern regExp_checkRoad6=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7$");
static Pattern regExp_checkRoad7=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7$");
static Pattern regExp_checkRoad8=Pattern.compile("^[\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?\\-[0-9]+(\u5F04|\u53F7)$");
static Pattern invalidAddrStartRegx=Pattern.compile("^[,\\(\\)\\-\\.\\&\\/\"\']");
static Pattern invalidAddrNotationRegx=Pattern.compile("[^一-龥\\w#\\/\\-\\\\]+");
static Pattern invalidAddrNotationRegx=Pattern.compile("[^一-龥\\w#\\/\\-\\\\]+");
static Pattern regExp_splitAddress1=Pattern.compile("\\s+|\u3000|\u3001|\uFF0C|,|/|;");
static Pattern regExp_splitAddress2=Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?)");
static Pattern regExp_splitAddress2=Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?)");
static Pattern regExp_checkRoadNo1=Pattern.compile("^[0-9]+(\u5F04|\u53F7)$");
static Pattern regExp_replaceRoadNo1=Pattern.compile("[0-9]+(\u53F7)");
static Pattern regExp_replaceRoadNo2=Pattern.compile("[0-9]+(\u5F04)");
static Pattern[] address_regExp_arr=new Pattern[]{
Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?\\-[0-9]+(\u5F04|\u53F7))")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7?\\-[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7?\\-[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7))")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+)")
Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)?\\-[0-9]+(\u5F04|\u53F7))")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04[0-9]+\u53F7?\\-[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7?\\-[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u652F\u5F04)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7)[0-9]+\u53F7)")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+(\u5F04|\u53F7))")
, Pattern.compile("^([\u4e00-\u9fa5]{2,15}(\u9053|\u8DEF|\u8857)[一二三四五六七八九十\\d]+)")
};
static Pattern address_regExp_1=Pattern.compile("^(([\u4e00-\u9fa5]{2,30}(\u5927\u9053|\u8DEF|街|道)([一二三四五六七八九十\\d]+(\u5F04|\u53F7))?)+)([\u4e00-\u9fa5\\.·]{3,15})([\\w]+.*)");
static Pattern address_regExp_2=Pattern.compile("^([\u4e00-\u9fa5]{2,30}(\u5927\u9053|\u8DEF|街|道)([一二三四五六七八九十\\d]+(\u5F04|\u53F7)))(.*)");
static Pattern address_regExp_3=Pattern.compile("^([\u4e00-\u9fa5\\.·]{4,30})([第一二三四五六七八九十\\w东南西北甲乙丙]+(房|单元|侧|区|#|栋|幢|座|号|楼).*)");
static Pattern address_regExp_4=Pattern.compile("^(([\u4e00-\u9fa5]{4,30}([\\d]+米)?)+)([第一二三四五六七八九十\\w东南西北甲乙丙]+(房|单元|侧|区|#|栋|幢|座|号|楼).*)");
static Pattern address_regExp_5=Pattern.compile("^([\u4e00-\u9fa5\\.·]{4,30})([\\w\\-]+.*)");
static Pattern address_regExp_1=Pattern.compile("^(([\u4e00-\u9fa5]{2,30}(\u5927\u9053|\u8DEF|街|道)([一二三四五六七八九十\\d]+(\u5F04|\u53F7))?)+)([\u4e00-\u9fa5\\.·]{3,15})([\\w]+.*)");
static Pattern address_regExp_2=Pattern.compile("^([\u4e00-\u9fa5]{2,30}(\u5927\u9053|\u8DEF|街|道)([一二三四五六七八九十\\d]+(\u5F04|\u53F7)))(.*)");
static Pattern address_regExp_3=Pattern.compile("^([\u4e00-\u9fa5\\.·]{4,30})([第一二三四五六七八九十\\w东南西北甲乙丙]+(房|单元|侧|区|#|栋|幢|座|号|楼).*)");
static Pattern address_regExp_4=Pattern.compile("^(([\u4e00-\u9fa5]{4,30}([\\d]+米)?)+)([第一二三四五六七八九十\\w东南西北甲乙丙]+(房|单元|侧|区|#|栋|幢|座|号|楼).*)");
static Pattern address_regExp_5=Pattern.compile("^([\u4e00-\u9fa5\\.·]{4,30})([\\w\\-]+.*)");
static String room_houseSuffix="[幢号座楼栋#]+";
static String room_unitSuffix="[单元梯座]+";
static String room_numSuffix="[房室号]{0,2}";
static String room_houseSuffix="[幢号座楼栋#]+";
static String room_unitSuffix="[单元梯座]+";
static String room_numSuffix="[房室号]{0,2}";
static Pattern[] room_regExp_arr2=new Pattern[]{
Pattern.compile(String.format("([\\w]+)%s([\\w]+)%s[\\d]+层([\\w]+)%s$", room_houseSuffix, room_unitSuffix, room_numSuffix))
Pattern.compile(String.format("([\\w]+)%s([\\w]+)%s[\\d]+层([\\w]+)%s$", room_houseSuffix, room_unitSuffix, room_numSuffix))
, Pattern.compile(String.format("([\\w]+)%s([\\w]+)%s([\\w]+)%s$", room_houseSuffix, room_unitSuffix, room_numSuffix))
, Pattern.compile(String.format("([\\w]+)%s([\\w]+)\\-([\\w]+)%s$", room_houseSuffix, room_numSuffix))
, Pattern.compile(String.format("([\\w]+)%s()[\\d]+层([\\w]+)%s$", room_houseSuffix, room_numSuffix))
, Pattern.compile(String.format("([\\w]+)%s()[\\d]+层([\\w]+)%s$", room_houseSuffix, room_numSuffix))
, Pattern.compile(String.format("([\\w]+)\\-([\\w]+)\\-([\\w]+)%s$", room_numSuffix))
, Pattern.compile(String.format("([\\w]+)\\\\([\\w]+)\\\\([\\w]+)$"))
, Pattern.compile(String.format("()([\\w]+)\\/([\\w]+)$"))
@@ -78,9 +78,9 @@ public class AddressParser {
};
//替换重复的镇名或路名: 千灯镇千灯镇黄浦路
//替换重复的镇名或路名: 千灯镇千灯镇黄浦路
static String replaceRepeatAddr(String address){
Pattern placeRegx=Pattern.compile("([^镇.]{2,5}镇)");
Pattern placeRegx=Pattern.compile("([^镇.]{2,5}镇)");
Matcher matcher=placeRegx.matcher(address);
if(matcher.find()){
String place=matcher.group(1);
@@ -94,7 +94,7 @@ public class AddressParser {
}
}
placeRegx=Pattern.compile("([^路.]{2,5}路)");
placeRegx=Pattern.compile("([^路.]{2,5}路)");
matcher=placeRegx.matcher(address);
if(matcher.find()){
String place=matcher.group(1);
@@ -139,7 +139,7 @@ public class AddressParser {
if(cityParents!=null){
for(int k=0; k<cityParents.length; k++){
if(isEmpty(cityParents[k]))continue;
Pattern cityParentRegx=Pattern.compile("^"+cityParents[k]+"(省|市|县)?");
Pattern cityParentRegx=Pattern.compile("^"+cityParents[k]+"(省|市|县)?");
Matcher matcher=cityParentRegx.matcher(address);
while(matcher.find()){
@@ -155,7 +155,7 @@ public class AddressParser {
for(int k=0; k<cityParents.length; k++){
if(isEmpty(cityParents[k]))continue;
Pattern cityParentRegx=Pattern.compile(cityParents[k]+"(省|市|县)");
Pattern cityParentRegx=Pattern.compile(cityParents[k]+"(省|市|县)");
Matcher matcher=cityParentRegx.matcher(address);
while(matcher.find()){
String address2=address.substring(matcher.start());
@@ -194,10 +194,10 @@ public class AddressParser {
if(districts!=null){
for(int i=0; i<districts.length; i++){
if(isEmpty(districts[i]))continue;
Pattern districtRoadRegx=Pattern.compile("^"+districts[i]+"[^区县市]{0,1}(路|街|大道|镇|道)");
Pattern districtRoadRegx=Pattern.compile("^"+districts[i]+"[^区县市]{0,1}(路|街|大道|镇|道)");
if(districtRoadRegx.matcher(address).find())continue;
Pattern districtSuffixRegx=Pattern.compile("^"+districts[i]+"(区|县|市)?");
Pattern districtSuffixRegx=Pattern.compile("^"+districts[i]+"(区|县|市)?");
matcher=districtSuffixRegx.matcher(address);
if(matcher.find()){
rt[0]=districts[i];
@@ -231,10 +231,10 @@ public class AddressParser {
return null;
}
//替换省市的名称,如:上海市上海青浦区黄浦路34弄2号,返回:黄浦路34弄2号
//替换省市的名称,如:上海市上海青浦区黄浦路34弄2号,返回:黄浦路34弄2号
/**
* rt[0]: 区域
* rt[1]: 地址
* rt[0]: 区域
* rt[1]: 地址
* @param city
* @param origAddress
* @return
@@ -245,7 +245,7 @@ public class AddressParser {
}
/**
* 匹配多个地址
* 匹配多个地址
* @param city
*/
static List<String> splitMutilAddr(String city, String address){
@@ -358,7 +358,7 @@ public class AddressParser {
addresses.add(address);
}else{
/**
* 匹配多个地址
* 匹配多个地址
*/
addresses=splitMutilAddr(city, address1);
if(addresses.size()==0){
@@ -369,11 +369,11 @@ public class AddressParser {
}
/**
* result[0]: 城市
* result[1]: 区域
* result[2]: 地址
* result[3]: 小区名
* result[4]: 楼号室号
* result[0]: 城市
* result[1]: 区域
* result[2]: 地址
* result[3]: 小区名
* result[4]: 楼号室号
*
* @param city
* @param origAddress
@@ -396,19 +396,19 @@ public class AddressParser {
String name=null;
String restAddr=null;
String city = null;
//提取城市
//提取城市
String[] rt=parseCity(origAddress);
origAddress=rt[1];
if(!isEmpty(rt[0])){
city=rt[0];
}
//去除省名城市名区等
//去除省名城市名区等
String[] rt2=doReplaceDistrict(city, origAddress, true);
if(rt2!=null){
addressResult.region=rt2[0];
origAddress=rt2[1];
}else if(isEmpty(city)){
//提取区域
//提取区域
rt2=parseRegion(origAddress);
if(rt2!=null){
city=rt2[0];
@@ -417,7 +417,7 @@ public class AddressParser {
}
if(!isEmpty(addressResult.region)){
Pattern regionRegx=Pattern.compile("^"+addressResult.region+"(区|县|市)?(房价|均价)?$");
Pattern regionRegx=Pattern.compile("^"+addressResult.region+"(区|县|市)?(房价|均价)?$");
matcher=regionRegx.matcher(origAddress);
if(matcher.find()){
addressResult.city=city;
@@ -428,7 +428,7 @@ public class AddressParser {
int matchType=0;
/**
* 解析室号
* 解析室号
*/
for(int k=0; k<room_regExp_arr1.length; k++){
Pattern pattern=room_regExp_arr1[k];
@@ -467,10 +467,10 @@ public class AddressParser {
}
}
/**
* 如果室号解析失败,解析地址
* 如果室号解析失败,解析地址
*/
if(matchType==0){
//解析标准地址带路号弄
//解析标准地址带路号弄
for(Pattern pattern: address_regExp_arr){
matcher=pattern.matcher(origAddress);
if(matcher.find()){
@@ -482,7 +482,7 @@ public class AddressParser {
}
/**
* 如果标准地址解析失败,用非标准地址继续解析地址
* 如果标准地址解析失败,用非标准地址继续解析地址
*/
if(matchType==0){
@@ -551,7 +551,7 @@ public class AddressParser {
}
/**
* 检查地址中是否带城市名的小区名
* 检查地址中是否带城市名的小区名
*
* @param preCity
* @param address
@@ -585,11 +585,11 @@ public class AddressParser {
String[] districts=city_districts.get(city);
for(String district: districts){
if(isEmpty(district))continue;
Pattern districtRoadRegx=Pattern.compile("^"+district+"[^区县市]{0,1}(路|街|大道|镇|道)");
Pattern districtRoadRegx=Pattern.compile("^"+district+"[^区县市]{0,1}(路|街|大道|镇|道)");
if(districtRoadRegx.matcher(address).find())continue;
Pattern districtSuffixRegx=Pattern.compile("^"+district+"(区|县|市)?(房价|均价)?$");
Pattern districtSuffixRegx=Pattern.compile("^"+district+"(区|县|市)?(房价|均价)?$");
Matcher matcher=districtSuffixRegx.matcher(address);
if(matcher.find()){
rt=new String[2];
@@ -609,19 +609,19 @@ public class AddressParser {
String address=origAddress;
for(int k=0; k<provinces.length; k++){
if(isEmpty(provinces[k]))continue;
Pattern provinceRegx=Pattern.compile("^"+provinces[k]+"(省|回族自治区|自治区|维吾尔自治区)?");
Pattern notProvinceRegx=Pattern.compile("^"+provinces[k]+"[^省市]{0,1}(路|街|大道|镇|道|市)");
Pattern provinceRegx=Pattern.compile("^"+provinces[k]+"(省|回族自治区|自治区|维吾尔自治区)?");
Pattern notProvinceRegx=Pattern.compile("^"+provinces[k]+"[^省市]{0,1}(路|街|大道|镇|道|市)");
Matcher notMatcher=notProvinceRegx.matcher(address);
Matcher matcher=provinceRegx.matcher(address);
if(matcher.find() && !notMatcher.find()){
province=provinces[k];
if(province.equals("上海")
||province.equals("北京")
||province.equals("天津")
||province.equals("重庆")
||province.equals("香港")
||province.equals("澳门")
if(province.equals("上海")
||province.equals("北京")
||province.equals("天津")
||province.equals("重庆")
||province.equals("香港")
||province.equals("澳门")
){
break;
}
@@ -637,17 +637,17 @@ public class AddressParser {
if(province==null){
for(int k=0; k<provinces.length; k++){
if(isEmpty(provinces[k]))continue;
Pattern provinceRegx=Pattern.compile(provinces[k]+"(省|回族自治区|自治区|维吾尔自治区)");
Pattern provinceRegx=Pattern.compile(provinces[k]+"(省|回族自治区|自治区|维吾尔自治区)");
Matcher matcher=provinceRegx.matcher(address);
if(matcher.find()){
province=provinces[k];
if(province.equals("上海")
||province.equals("北京")
||province.equals("天津")
||province.equals("重庆")
||province.equals("香港")
||province.equals("澳门")
if(province.equals("上海")
||province.equals("北京")
||province.equals("天津")
||province.equals("重庆")
||province.equals("香港")
||province.equals("澳门")
){
break;
}
@@ -700,8 +700,8 @@ public class AddressParser {
private static String matchCity(String city, String address){
if(isEmpty(city))return null;
boolean matched=false;
Pattern cityParentRegx=Pattern.compile("^"+city+"(市|县)?");
Pattern notCityParentRegx=Pattern.compile("^"+city+"[^区县市]{0,1}(路|街|大道|镇|道)");
Pattern cityParentRegx=Pattern.compile("^"+city+"(市|县)?");
Pattern notCityParentRegx=Pattern.compile("^"+city+"[^区县市]{0,1}(路|街|大道|镇|道)");
Matcher notMatcher=notCityParentRegx.matcher(address);
Matcher matcher=cityParentRegx.matcher(address);
if(matcher.find() && !notMatcher.find()){
@@ -709,7 +709,7 @@ public class AddressParser {
matched=true;
}
if(!matched){
cityParentRegx=Pattern.compile(city+"(市|县)");
cityParentRegx=Pattern.compile(city+"(市|县)");
matcher=cityParentRegx.matcher(address);
if(matcher.find()){
address=matcher.replaceAll("").trim();
@@ -731,34 +731,34 @@ public class AddressParser {
public static void main(String[] args){
String address="广东深圳韶南大道北75号";
String address="广东深圳韶南大道北75号";
long startTime=System.currentTimeMillis();
String region= AddressParser.getRegionByAddress(address);
System.out.println(region);
/*startTime=System.currentTimeMillis();
address="浙江嘉兴市南湖区新丰工业区";
address="浙江嘉兴市南湖区新丰工业区";
rt=parseAddressWithRoom(null, address);
System.out.println(rt);
System.out.println("time: "+(System.currentTimeMillis()-startTime));
address="浙江省宁波松江沪松公路18弄公册公园";
address="浙江省宁波松江沪松公路18弄公册公园";
rt=parseAddressWithRoom(null, address);
System.out.println(rt);
address="浙江省宁波市松江沪松公公册公园A区18号a18-202";
address="浙江省宁波市松江沪松公公册公园A区18号a18-202";
rt=parseAddressWithRoom(null, address);
System.out.println(rt);
address="浙江省宁波市松江沪松公公册公园a18-202";
address="浙江省宁波市松江沪松公公册公园a18-202";
rt=parseAddressWithRoom(null, address);
System.out.println(rt);
address="浙江省宁波市松江路A区18号a18-202";
address="浙江省宁波市松江路A区18号a18-202";
rt=parseAddressWithRoom(null, address);
System.out.println(rt);
startTime=System.currentTimeMillis();
System.out.println( AddressParser.parseAddressWithRoom(null,"上海市松江沪松公路1138号、\"99弄、.#106弄"));
System.out.println( AddressParser.parseAddressWithRoom(null,"上海市松江沪松公路1138号、\"99弄、.#106弄"));
System.out.println("time: "+(System.currentTimeMillis()-startTime));*/
}
@@ -17,11 +17,11 @@ public class AddressUtils {
*/
public static void main(String[] args) {
AddressUtils task = new AddressUtils();
System.out.println(task.getRoadNameBySplitWord("上海市长宁区天山西路267弄"));
System.out.println(task.getRoadNameBySplitWord("上海市长宁区天山西路267弄"));
}
//分词获取路名
//分词获取路名
public static String getRoadNameBySplitWord(String key) {
String url = "";
try {
@@ -74,23 +74,23 @@ public class BaiduAddressParser {
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
// 发送请求参数
out.print(param);
// flush输出流的缓冲
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
@@ -98,10 +98,10 @@ public class BaiduAddressParser {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
@@ -127,7 +127,7 @@ public class BaiduAddressParser {
}
public static void main(String[] args){
System.out.println(BaiduAddressParser.getRegionByAddress("","广东深圳深圳市龙华汽车站建成路"));
System.out.println(BaiduAddressParser.getRegionByAddress("","广东深圳深圳市龙华汽车站建成路"));
}
}
@@ -12,7 +12,7 @@ import java.util.Set;
public class CollectionUtils extends org.apache.commons.collections.CollectionUtils {
/**
* 对一个列表进行分组
* 对一个列表进行分组
*
* @param <K>
* @param <V>
@@ -38,7 +38,7 @@ public class CollectionUtils extends org.apache.commons.collections.CollectionUt
}
/**
* 对一个列表进行分组
* 对一个列表进行分组
*
* @param <K>
* @param <V>
@@ -61,7 +61,7 @@ public class CollectionUtils extends org.apache.commons.collections.CollectionUt
}
/**
* 将一个列表转换成另一个列表
* 将一个列表转换成另一个列表
*
* @param <O>
* @param <I>
@@ -84,7 +84,7 @@ public class CollectionUtils extends org.apache.commons.collections.CollectionUt
}
/**
* 将一个列表转换成另一个列表。如果closure的execute方法返回null则丢弃当前结果
* 将一个列表转换成另一个列表。如果closure的execute方法返回null则丢弃当前结果
*
* @param <O>
* @param <I>
@@ -9,7 +9,7 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 自动解析老版备份(已废弃)
* 自动解析老版备份(已废弃)
* @author yk
*
*/
@@ -30,26 +30,26 @@ public class InfoAnalyUtil {
// private final static List<String> direction = new ArrayList<String>();
private final static List<String> fitment = new ArrayList<String>(
Arrays.asList("装修", "装修情况", "装修程度", "房屋情况"));
Arrays.asList("装修", "装修情况", "装修程度", "房屋情况"));
private final static List<String> totalPrice = new ArrayList<String>(
Arrays.asList("总价", "出售价格", "售价", "到手价", "出售总价", "房价", "价格", "房源价格"));
Arrays.asList("总价", "出售价格", "售价", "到手价", "出售总价", "房价", "价格", "房源价格"));
private final static List<String> roomHallToilet = new ArrayList<String>(
Arrays.asList("户型", "房型", "房型面积"));
Arrays.asList("户型", "房型", "房型面积"));
private final static List<String> area = new ArrayList<String>(
Arrays.asList("建筑面积", "面积","产权面积","产证面积","房型面积"));
Arrays.asList("建筑面积", "面积","产权面积","产证面积","房型面积"));
private final static List<String> floorHeight = new ArrayList<String>(
Arrays.asList("楼层", "楼栋", "所在楼层", "所在层数", "房屋楼层"));
Arrays.asList("楼层", "楼栋", "所在楼层", "所在层数", "房屋楼层"));
private final static List<String> direction = new ArrayList<String>(
Arrays.asList("朝向", "房屋朝向", "概况"));
Arrays.asList("朝向", "房屋朝向", "概况"));
private static Map<String,String> infoMap;
private static String key = "房型面积";
private static String key = "房型面积";
public static Map<String,String> getInforMation(String links) throws UnsupportedEncodingException{
infoMap = new HashMap<String,String>();
@@ -62,7 +62,7 @@ public class InfoAnalyUtil {
byte bytes[] = {(byte) 0xC2,(byte) 0xA0};
String UTFSpace = new String(bytes,"utf-8");
arr[i] = arr[i].replaceAll(UTFSpace, "");
arr[i].replaceAll(" | | ", "");
arr[i].replaceAll(" | | ", "");
if(arr[i].contains("[")){
arr[i] = "";
}
@@ -81,7 +81,7 @@ public class InfoAnalyUtil {
}
/**
* 最后规范化输出数据
* 最后规范化输出数据
* @param infoMap2
*/
private static void dealMap(Map<String, String> infoMap2) {
@@ -162,25 +162,25 @@ public class InfoAnalyUtil {
}
}
String area = infoMap.get("area");
if(area.contains("㎡")){
infoMap.put("area", area.substring(0, area.indexOf("㎡")));
if(area.contains("㎡")){
infoMap.put("area", area.substring(0, area.indexOf("㎡")));
}
if(area.contains("平米")){
infoMap.put("area", area.substring(0, area.indexOf("平米")));
if(area.contains("平米")){
infoMap.put("area", area.substring(0, area.indexOf("平米")));
}
if(area.contains("平方米")){
infoMap.put("area", area.substring(0, area.indexOf("平方米")));
if(area.contains("平方米")){
infoMap.put("area", area.substring(0, area.indexOf("平方米")));
}
infoMap.remove("roomHallToilet");
}
/**
* 判断是否含有特殊字段
* 判断是否含有特殊字段
* @param keyContent
*/
private static void judgeContainKey(String keyContent) {
if (keyContent.contains(key)) {
String[] txt = keyContent.split("㎡");
String[] txt = keyContent.split("㎡");
if (txt.length >= 1) {
String content = txt[0];
for (int j = 1; j < content.length() + 1; j++) {
@@ -189,7 +189,7 @@ public class InfoAnalyUtil {
String content2 = content.substring(length - j - 1, length);
if (content1.matches("^\\d+$|^\\d+\\.\\d+$|-\\d+$")
&& !content2.matches("^\\d+$|^\\d+\\.\\d+$|-\\d+$")) {
infoMap.put("area", content1 + "㎡");
infoMap.put("area", content1 + "㎡");
infoMap.put("roomHallToilet",
content.substring(5, length - j));
break;
@@ -200,35 +200,35 @@ public class InfoAnalyUtil {
}
/**
* 判断信息是否全
* 判断信息是否全
* @param arr
*/
private static void judgeInfoIsFull(String[] arr) {
if (infoMap.get("room") == null) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].contains("室")&&!arr[i].contains("厅")) {
if (arr[i].contains("室")&&!arr[i].contains("厅")) {
infoMap.put("room", arr[i].substring(0, arr[i].length()-1));
}
}
}
if (infoMap.get("hall") == null) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].contains("厅")&&!arr[i].contains("室")) {
if (arr[i].contains("厅")&&!arr[i].contains("室")) {
infoMap.put("hall", arr[i].substring(0, arr[i].length()-1));
}
}
}
if (infoMap.get("toilet") == null) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].contains("卫")&&!arr[i].contains("室")) {
if (arr[i].contains("卫")&&!arr[i].contains("室")) {
infoMap.put("toilet", arr[i].substring(0, arr[i].length()-1));
}
}
}
if (infoMap.get("area") == null) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].contains("㎡")) {
String[] number = arr[i].split("㎡");
if (arr[i].contains("㎡")) {
String[] number = arr[i].split("㎡");
if (number.length >= 1) {
boolean result = number[0].matches("[0-9]+");
if (result == true) {
@@ -238,7 +238,7 @@ public class InfoAnalyUtil {
boolean result = arr[i - 1]
.matches("^\\d+$|^\\d+\\.\\d+$|-\\d+$");
if (result == true) {
infoMap.put("area", arr[i - 1] + "㎡");
infoMap.put("area", arr[i - 1] + "㎡");
}
}
}
@@ -248,13 +248,13 @@ public class InfoAnalyUtil {
}
/**
* 根据关键字处理数据
* 根据关键字处理数据
* @param text
* @param nexText
*/
public static void judgeType(String text, String nexText) {
if (text.contains(":") || text.contains(":")) {
String[] result = text.split(":|:|:");
if (text.contains(":") || text.contains(":")) {
String[] result = text.split(":|:|:");
if (result.length <= 1) {
OutPutResult(result[0], nexText);
} else {
@@ -269,9 +269,9 @@ public class InfoAnalyUtil {
if (text.contains(vo)) {
String[] result = text.split(vo);
if (result.length > 1 && hasDigit(result[1])) {
if (result[1].contains("万")) {
if (result[1].contains("万")) {
result[1] = result[1].substring(0,
result[1].indexOf("万"));
result[1].indexOf("万"));
}
if(isDecimal(result[1])){
if(result[1].contains(".")){
@@ -361,14 +361,14 @@ public class InfoAnalyUtil {
}
/**
* 输出
* 输出
* @param text1
* @param text2
*/
public static void OutPutResult(String text1, String text2) {
if (totalPrice.contains(text1)) {
if (text2.contains("万")) {
text2 = text2.substring(0, text2.indexOf("万"));
if (text2.contains("万")) {
text2 = text2.substring(0, text2.indexOf("万"));
}
if(isDecimal(text2)){
if(text2.contains(".")){
@@ -437,10 +437,10 @@ public class InfoAnalyUtil {
return Pattern.compile("([1-9]+[0-9]*|0)(\\.[\\d]+)?").matcher(str).matches();
}
//中文和阿拉伯数字转换
//中文和阿拉伯数字转换
public static String fn2(String number)
{
String hanzi[] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ,"两"};
String hanzi[] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ,"两"};
String alabo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ,"2"};
for (int i = 0; i < 11; i++)
if (number.equals(hanzi[i]))
@@ -449,17 +449,17 @@ public class InfoAnalyUtil {
}
// /**
// * 关键字
// * 关键字
// * @author yk
// *
// */
// public enum keyword{
// fitment("装修"),
// area("面积"),
// floorHeight("楼层"),
// roomHallToilet("户型"),
// direction("朝向"),
// totalPrice("总价");
// fitment("装修"),
// area("面积"),
// floorHeight("楼层"),
// roomHallToilet("户型"),
// direction("朝向"),
// totalPrice("总价");
//
// public final String value;
//
@@ -473,15 +473,15 @@ public class InfoAnalyUtil {
// }
/**
* 室厅卫
* 室厅卫
* @author yk
*
*/
public enum roomHallToiletType{
room("室"),
room2("房"),
hall("厅"),
toilet("卫");
room("室"),
room2("房"),
hall("厅"),
toilet("卫");
private final String value;
@@ -495,7 +495,7 @@ public class InfoAnalyUtil {
}
/**
* 获取匹配规则
* 获取匹配规则
*/
// private static void getModeList() {
// List<AutoModeAnaly> list = autoModeAnalyDao.findAllByType(null);
@@ -218,10 +218,10 @@ public class JQueryUtil {
for(Element child : element.children()) {
if(child.tagName().matches("(?:table|tbody|tr|td)")) {
for(Element td : child.select("td")) {
childList.add(td.text().replaceAll("\\s| ", ""));
childList.add(td.text().replaceAll("\\s| ", ""));
}
} else {
childList.add(child.text().replaceAll("\\s| ", ""));
childList.add(child.text().replaceAll("\\s| ", ""));
}
}
list.add(childList);
@@ -4,19 +4,19 @@ import java.util.List;
import java.util.Map;
/**
* 正则匹配的结果
* 正则匹配的结果
*
* @author Administrator
*
*/
public class MatcherResult {
/**
* 匹配结果
* 匹配结果
*/
private boolean found = false;
/**
* 原始正则
* 原始正则
*/
private String orgPattern;
@@ -36,9 +36,9 @@ public class MatcherResult {
this.found = found;
}
// 匹配的参数映射
// 匹配的参数映射
private Map<String, String> params;
// 正则原始值
// 正则原始值
private List<String> groups;
public Map<String, String> getParams() {
@@ -62,7 +62,7 @@ public class MatcherResult {
}
/**
* 获得参数值
* 获得参数值
*
* @param key
* @return
@@ -75,7 +75,7 @@ public class MatcherResult {
}
/**
* 得到匹配上的正则字符串
* 得到匹配上的正则字符串
*
* @return
*/
@@ -8,14 +8,14 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则表达式匹配,主要增强的功能是可以使用变量名进行匹配 变量名比如: [$mod(\d)]
* 正则表达式匹配,主要增强的功能是可以使用变量名进行匹配 变量名比如: [$mod(\d)]
*
* @author Administrator
*
*/
public class RegexMatcher {
/**
* 匹配字符串与伪正则表达式的关系,并返回想要取得的值 需要获得原始正则匹配到的结果
* 匹配字符串与伪正则表达式的关系,并返回想要取得的值 需要获得原始正则匹配到的结果
*
* @param s
* @param regex
@@ -30,11 +30,11 @@ public class RegexMatcher {
Pattern p = Pattern.compile(newRegex);
Matcher matcher = p.matcher(s);
if (!matcher.find()) {
// 没找到
// 没找到
matcherResult.setFound(false);
return matcherResult;
}
// 找到了
// 找到了
matcherResult.setFound(true);
Map<String, String> params = new HashMap<String, String>();
for (Map.Entry<String, Integer> entry : paramsMap.entrySet()) {
@@ -55,9 +55,9 @@ public class RegexMatcher {
}
/**
* 根据原始正则,重写正则规则,返回出新的正则表达式,同时会返回变量名和group位置的对应关系 比如输入的正则为:
* "http://[$city].anjuke.com/sale/(\w*)/a2-m[$mod(\d)]-t3" 则返回的正则表达式为:
* "http://(\w*).anjuke.com/sale/(\w*)/a2-m(\d)-t3" 同时返回的变量映射为: city:1 mod:3
* 根据原始正则,重写正则规则,返回出新的正则表达式,同时会返回变量名和group位置的对应关系 比如输入的正则为:
* "http://[$city].anjuke.com/sale/(\w*)/a2-m[$mod(\d)]-t3" 则返回的正则表达式为:
* "http://(\w*).anjuke.com/sale/(\w*)/a2-m(\d)-t3" 同时返回的变量映射为: city:1 mod:3
*
*/
private static String rewriteRegex(String regex, Map<String, Integer> paramsMap) {
@@ -66,21 +66,21 @@ public class RegexMatcher {
int len = regex.length();
Integer group = 1;
while (true) {
// 首先查找[$开头的,因为我们是用这样的标识符进行标识的
// 首先查找[$开头的,因为我们是用这样的标识符进行标识的
int index = regex.indexOf("[$", fromIndex);
if (index >= 0) {
// int endIndex = regex.indexOf("]", index);
int endIndex = findRightBracket(regex, index);
if (endIndex > 0) {
// 找到了$[和]部分
// 取出fromIndex和index之间的内容,这部分内容是没有变量定义的
// 找到了$[和]部分
// 取出fromIndex和index之间的内容,这部分内容是没有变量定义的
String noParamValue = regex.substring(fromIndex, index);
ret.append(noParamValue);
group += countGroup(noParamValue);
// 变量部分,+2为跳过$[
// 变量部分,+2为跳过$[
String param = regex.substring(index + 2, endIndex);
// 转换变量部分,如果变量部分有(则取出()中内容,否则用\w*代替
// 转换变量部分,如果变量部分有(则取出()中内容,否则用\w*代替
String paramName = getParamName(param);
String paramRegex = getParamRegex(param);
ret.append(paramRegex);
@@ -88,16 +88,16 @@ public class RegexMatcher {
paramsMap.put(paramName, group);
group++;
// +1为跳过已经找到的结束符号]
// +1为跳过已经找到的结束符号]
fromIndex = endIndex + 1;
} else {
// 只有$[,没有结束的]
// 只有$[,没有结束的]
System.out.println("Error: No ] in parsing regex " + regex);
paramsMap.clear();
return regex;
}
} else {
// 没有找到[$部分了
// 没有找到[$部分了
String noParamValue = regex.substring(fromIndex, len);
ret.append(noParamValue);
break;
@@ -107,8 +107,8 @@ public class RegexMatcher {
}
/**
* 在字符串中找右中括号,如果没找到返回-1 如果中间碰到[则会跳过一个]
* 类似的输入如:http://esf.sh.soufun.com/house/i32-[$kw([a-zA-Z0-9%]*)] 替换掉int
* 在字符串中找右中括号,如果没找到返回-1 如果中间碰到[则会跳过一个]
* 类似的输入如:http://esf.sh.soufun.com/house/i32-[$kw([a-zA-Z0-9%]*)] 替换掉int
* endIndex = regex.indexOf("]", index);
*
* @param s
@@ -142,7 +142,7 @@ public class RegexMatcher {
}
/**
* 统计在没有正则变量时分组的个数 分组是用()来进行的
* 统计在没有正则变量时分组的个数 分组是用()来进行的
*
* @param noParamValue
* @return
@@ -154,7 +154,7 @@ public class RegexMatcher {
int index = noParamValue.indexOf("(", fromIndex);
if (index >= 0) {
ret++;
// +1为跳过(
// +1为跳过(
fromIndex = index + 1;
} else {
break;
@@ -164,7 +164,7 @@ public class RegexMatcher {
}
/**
* 获得变量名字 比如输入为: city => city mod(\d) => mod
* 获得变量名字 比如输入为: city => city mod(\d) => mod
*
* @param s
* @return
@@ -172,14 +172,14 @@ public class RegexMatcher {
private static String getParamName(String s) {
int index = s.indexOf("(");
if (index > 0) {
// 有(,则返回(之前的内容
// 有(,则返回(之前的内容
return s.substring(0, index);
}
return s;
}
/**
* 获得变量正则部分 比如: city => (\w*) mod(\d) => (\d)
* 获得变量正则部分 比如: city => (\w*) mod(\d) => (\d)
*
* @param s
* @return
@@ -14,32 +14,32 @@ import org.jsoup.helper.StringUtil;
public class SellInfoUtil {
private final static List<String> totalPrice = new ArrayList<String>(
Arrays.asList("价格", "总价", "出售价格", "售价", "到手价", "出售总价", "房价", "房源价格"));
Arrays.asList("价格", "总价", "出售价格", "售价", "到手价", "出售总价", "房价", "房源价格"));
private final static List<String> area = new ArrayList<String>(
Arrays.asList("面积", "建筑面积","产权面积","产证面积"));
Arrays.asList("面积", "建筑面积","产权面积","产证面积"));
private final static List<String> floorHeight = new ArrayList<String>(
Arrays.asList("楼层", "楼栋", "所在楼层", "所在层数", "房屋楼层"));
Arrays.asList("楼层", "楼栋", "所在楼层", "所在层数", "房屋楼层"));
private final static List<String> direction = new ArrayList<String>(
Arrays.asList("朝向", "房屋朝向", "概况"));
Arrays.asList("朝向", "房屋朝向", "概况"));
private final static List<String> fitmentcontent = new ArrayList<String>(
Arrays.asList("毛坯", "简装修", "中装修", "精装修", "豪华装修", "精装", "豪装",
"一般装修", "普通装修", "无装修", "中等装修", "毛坯房", "中装","简单装修"));
Arrays.asList("毛坯", "简装修", "中装修", "精装修", "豪华装修", "精装", "豪装",
"一般装修", "普通装修", "无装修", "中等装修", "毛坯房", "中装","简单装修"));
private final static List<String> key_direction = new ArrayList<String>(
Arrays.asList("南北","东西","东南","东北","西南","西北","东","南","西","北"));
Arrays.asList("南北","东西","东南","东北","西南","西北","东","南","西","北"));
public static Map<String,String> getInforMation(String links) throws UnsupportedEncodingException{
Map<String,String> infoMap = new HashMap<String,String>();
//总价
//总价
for(int i=0;i<totalPrice.size();i++){
if(links.contains(totalPrice.get(i))){
int x = links.indexOf(totalPrice.get(i)) + totalPrice.get(i).length()+1;
String priceStr = links.substring(x, links.length());
int y = x + priceStr.indexOf("万");
int y = x + priceStr.indexOf("万");
String price = links.substring(x, y);
if(isNumeric(price)){
int number = (int)(Float.valueOf(price) *10000);
@@ -48,34 +48,34 @@ public class SellInfoUtil {
}
}
}
//室
if(links.contains("室")){
String room = links.substring(links.indexOf("室")-1, links.indexOf("室"));
//室
if(links.contains("室")){
String room = links.substring(links.indexOf("室")-1, links.indexOf("室"));
boolean result = room.matches("[0-9]+");
if (!result) {
room = fn2(room);
}
infoMap.put("room", room);
}
//厅
if(links.contains("厅")){
String hall = links.substring(links.indexOf("厅")-1, links.indexOf("厅"));
//厅
if(links.contains("厅")){
String hall = links.substring(links.indexOf("厅")-1, links.indexOf("厅"));
boolean result = hall.matches("[0-9]+");
if (!result) {
hall = fn2(hall);
}
infoMap.put("hall", hall);
}
//卫
if(links.contains("卫")){
String toilet = links.substring(links.indexOf("卫")-1, links.indexOf("卫"));
//卫
if(links.contains("卫")){
String toilet = links.substring(links.indexOf("卫")-1, links.indexOf("卫"));
boolean result = toilet.matches("[0-9]+");
if (!result) {
toilet = fn2(toilet);
}
infoMap.put("toilet", toilet);
}
//朝向
//朝向
for(int i=0;i<direction.size();i++){
if(links.contains(direction.get(i))){
String directions = links.substring(links.indexOf(direction.get(i)), links.indexOf(direction.get(i))+8);
@@ -88,7 +88,7 @@ public class SellInfoUtil {
}
}
}
//装修
//装修
for(int i=0;i<fitmentcontent.size();i++){
if(links.contains(fitmentcontent.get(i))){
String fitment = fitmentcontent.get(i);
@@ -97,25 +97,25 @@ public class SellInfoUtil {
}
}
String baseArea = "";
//面积
//面积
for(int i=0;i<area.size();i++){
if(links.contains(area.get(i))){
int x = links.indexOf(area.get(i))+area.get(i).length();
String areaStr = links.substring(x, x+10);
String areas = "";
if(areaStr.contains("平米")){
areas = areaStr.substring(1, areaStr.indexOf("平米"));
}else if(areaStr.contains("㎡")){
areas = areaStr.substring(1, areaStr.indexOf("㎡"));
}else if(areaStr.contains("平方米")){
areas = areaStr.substring(1, areaStr.indexOf("平方米"));
if(areaStr.contains("平米")){
areas = areaStr.substring(1, areaStr.indexOf("平米"));
}else if(areaStr.contains("㎡")){
areas = areaStr.substring(1, areaStr.indexOf("㎡"));
}else if(areaStr.contains("平方米")){
areas = areaStr.substring(1, areaStr.indexOf("平方米"));
}
baseArea = areas;
infoMap.put("area", areas);
break;
}
}
//楼层
//楼层
for(int i=0;i<floorHeight.size();i++){
if(links.contains(floorHeight.get(i))){
int x = links.indexOf(floorHeight.get(i))+floorHeight.get(i).length();
@@ -156,7 +156,7 @@ public class SellInfoUtil {
}
}
if(StringUtil.isBlank(baseArea)){
Pattern pattern = Pattern.compile("[0-9]㎡");
Pattern pattern = Pattern.compile("[0-9]㎡");
Matcher matcher = pattern.matcher(links);
while (matcher.find()) {
baseArea = matcher.group(0);
@@ -164,7 +164,7 @@ public class SellInfoUtil {
}
String content = links.substring(0, links.indexOf(baseArea)+baseArea.length());
if(StringUtil.isBlank(baseArea)){
Pattern pattern1 = Pattern.compile(" ㎡");
Pattern pattern1 = Pattern.compile(" ㎡");
Matcher matcher1 = pattern1.matcher(links);
while (matcher1.find()) {
baseArea = matcher1.group(0);
@@ -174,18 +174,18 @@ public class SellInfoUtil {
content = links.substring(0, links.indexOf(baseArea));
String[] txt = content.split(" ");
String area = txt[txt.length-1];
if(area.contains("㎡")){
area = area.substring(0, area.indexOf("㎡"));
if(area.contains("㎡")){
area = area.substring(0, area.indexOf("㎡"));
}
infoMap.put("area", area);
}
return infoMap;
}
//中文和阿拉伯数字转换
//中文和阿拉伯数字转换
public static String fn2(String number)
{
String hanzi[] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ,"两"};
String hanzi[] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ,"两"};
String alabo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ,"2"};
for (int i = 0; i < 11; i++)
if (number.equals(hanzi[i]))
@@ -193,7 +193,7 @@ public class SellInfoUtil {
return "";
}
//判断是不是数字
//判断是不是数字
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
@@ -52,22 +52,22 @@ public class FieldProcess {
private String delCommonValue(String value){
if(value.equals("暂无")){
if(value.equals("暂无")){
return "";
}
if(value.equals("无")){
if(value.equals("无")){
return "";
}
if(value.indexOf("暂无资料")!=-1){
if(value.indexOf("暂无资料")!=-1){
return "";
}
if(value.indexOf("数据更新中")!=-1){
if(value.indexOf("数据更新中")!=-1){
return "";
}
if(value.indexOf("不详")!=-1){
if(value.indexOf("不详")!=-1){
return "";
}
@@ -79,8 +79,8 @@ public class FieldProcess {
private DBObject getCubagePercentValue(District district, DBObject obj){
if(null!=district.getCubagePercent()){
String value = delCommonValue(district.getCubagePercent());
if(value.indexOf("[容积率]")!=-1){
value = value.replace("[容积率]", "");
if(value.indexOf("[容积率]")!=-1){
value = value.replace("[容积率]", "");
}
double score = FieldValidator.score("cubage_percent", value);
@@ -88,7 +88,7 @@ public class FieldProcess {
value="";
}
if(!value.equals(district.getCubagePercent())){
System.out.println("[修改]"+district.getCubagePercent() + ":"+value);
System.out.println("[修改]"+district.getCubagePercent() + ":"+value);
obj.put("cubage_percent", value);
}
if(score>0){
@@ -129,7 +129,7 @@ public class FieldProcess {
value="";
}
if(!value.equals(district.getVirescencePercent())){
System.out.println("[修改]"+district.getVirescencePercent() + ":"+value);
System.out.println("[修改]"+district.getVirescencePercent() + ":"+value);
obj.put("virescence_percent", value);
}
if(score>0){
@@ -142,7 +142,7 @@ public class FieldProcess {
public DBObject getDeveloperValue(District district, DBObject obj){
if(null!=district.getDeveloper()){
String value = delCommonValue(district.getDeveloper());
String[] keys = {"集团","公司","置业","地产","房产","开发商","股份"};
String[] keys = {"集团","公司","置业","地产","房产","开发商","股份"};
boolean flag = false;
for(String key : keys){
if(value.indexOf(key)!=-1){
@@ -151,10 +151,10 @@ public class FieldProcess {
}
}
if(!flag){
System.out.println("无关键字:"+value);
System.out.println("无关键字:"+value);
}
if(!value.equals(district.getDeveloper())){
System.out.println("[修改]"+district.getDeveloper() + ":"+value);
System.out.println("[修改]"+district.getDeveloper() + ":"+value);
obj.put("developer", value);
}
@@ -166,7 +166,7 @@ public class FieldProcess {
public DBObject getEstateCompanyValue(District district, DBObject obj){
if(null!=district.getEstateCompany()){
String value = delCommonValue(district.getEstateCompany());
String[] keys = {"集团","物业","公司","物管","置业"};
String[] keys = {"集团","物业","公司","物管","置业"};
boolean flag = false;
for(String key : keys){
if(value.indexOf(key)!=-1){
@@ -175,10 +175,10 @@ public class FieldProcess {
}
}
if(!flag){
if(value.indexOf("参考价")!=-1){
if(value.indexOf("参考价")!=-1){
value="";
}
System.out.println(district.getName()+" 无关键字:"+district.getEstateCompany());
System.out.println(district.getName()+" 无关键字:"+district.getEstateCompany());
}
if(isInteger(value)){
@@ -187,7 +187,7 @@ public class FieldProcess {
if(!value.equals(district.getEstateCompany())){
obj.put("estate_company", value);
System.out.println("[修改]"+district.getEstateCompany() + ":"+value);
System.out.println("[修改]"+district.getEstateCompany() + ":"+value);
}
}
@@ -197,13 +197,13 @@ public class FieldProcess {
public DBObject getBuildAreaValue(District district, DBObject obj){
if(null!=district.getBuildArea()){
String value = delCommonValue(district.getBuildArea());
if(value.indexOf("万平方米")!=-1){
String val = value.substring(0, value.indexOf("万平方米"));
if(value.indexOf("万平方米")!=-1){
String val = value.substring(0, value.indexOf("万平方米"));
if(isDouble(val)){
int v = (int) (Double.parseDouble(val)*10000);
value = String.valueOf(v) + "平方米";
value = String.valueOf(v) + "平方米";
}else{
System.out.println("不是double且长度小于20:"+value+" ["+district.getName()+"]");
System.out.println("不是double且长度小于20:"+value+" ["+district.getName()+"]");
}
}
@@ -213,7 +213,7 @@ public class FieldProcess {
//double score = FieldValidator.score("build_area", value);
if(!value.equals(district.getBuildArea())){
obj.put("build_area", value);
System.out.println("[修改]"+district.getBuildArea() + ":"+value);
System.out.println("[修改]"+district.getBuildArea() + ":"+value);
}
}
return obj;
@@ -222,13 +222,13 @@ public class FieldProcess {
public DBObject getAllAreaValue(District district, DBObject obj){
if(null!=district.getAllArea()){
String value = delCommonValue(district.getAllArea());
if(value.indexOf("万平方米")!=-1){
String val = value.substring(0, value.indexOf("万平方米"));
if(value.indexOf("万平方米")!=-1){
String val = value.substring(0, value.indexOf("万平方米"));
if(isDouble(val)){
int v = (int) (Double.parseDouble(val)*10000);
value = String.valueOf(v) + "平方米";
value = String.valueOf(v) + "平方米";
}else{
System.out.println("不是double且长度小于20:"+value+" ["+district.getName()+"]");
System.out.println("不是double且长度小于20:"+value+" ["+district.getName()+"]");
}
}
@@ -238,7 +238,7 @@ public class FieldProcess {
//double score = FieldValidator.score("build_area", value);
if(!value.equals(district.getAllArea())){
obj.put("all_area", value);
System.out.println("[修改]"+district.getAllArea() + ":"+value);
System.out.println("[修改]"+district.getAllArea() + ":"+value);
}
}
return obj;
@@ -249,7 +249,7 @@ public class FieldProcess {
if(null!=district.getCarSite()){
String value = delCommonValue(district.getCarSite());
if(value.equals("0个")){
if(value.equals("0个")){
value = "";
}
if(value.equals("-")){
@@ -261,7 +261,7 @@ public class FieldProcess {
value = value.replace("<strong></strong>", "");
if(!value.equals(district.getCarSite())){
obj.put("car_site", value);
System.out.println("[修改]"+district.getCarSite() + ":"+value);
System.out.println("[修改]"+district.getCarSite() + ":"+value);
}
}
@@ -69,13 +69,13 @@ public class FieldValidator {
}
/**
* 字段验证,须先在后台添加字段验证器
* 字段验证,须先在后台添加字段验证器
*
* @param field
* 字段名
* 字段名
* @param obj
* 待验证的值
* @return 验证得分。100:没有该字段的验证规则
* 待验证的值
* @return 验证得分。100:没有该字段的验证规则
*/
public static double score(String field, Object obj) {
while (isloading) {
@@ -91,7 +91,7 @@ public class FieldValidator {
}
String str = obj.toString();
str = null == str ? "" : str.replaceAll("^[\\s ]*|[\\s ]*$", "");
str = null == str ? "" : str.replaceAll("^[\\s ]*|[\\s ]*$", "");
str = str.trim();
if ("".equals(str)) {
return 1;
@@ -216,10 +216,10 @@ public class FieldValidator {
public static void main(String[] args) {
System.out.println(score("all_area", "49950.00 平米"));
System.out.println(score("build_area", "200000.00 平米"));
System.out.println(score("alias", "别名1"));
// Pattern p = Pattern.compile("^\\d{2,4}(\\-|\\/|\\.|年)?(\\d{1,2}(\\-|\\/|\\.|月))?(\\d{1,2}(日|号)?)?$");
System.out.println(score("all_area", "49950.00 平米"));
System.out.println(score("build_area", "200000.00 平米"));
System.out.println(score("alias", "别名1"));
// Pattern p = Pattern.compile("^\\d{2,4}(\\-|\\/|\\.|年)?(\\d{1,2}(\\-|\\/|\\.|月))?(\\d{1,2}(日|号)?)?$");
// System.out.println(p.matcher("1999").matches());
}
}
@@ -90,7 +90,7 @@ public class Analyzer {
}
/**
* 用script脚本对解析后的数据进行处理
* 用script脚本对解析后的数据进行处理
* @param obj
* @param rule
*/
@@ -102,12 +102,12 @@ public class Analyzer {
// Object res = InvokeShell.invoke(rule.getScript(), obj);
if (rule.getAnaType() == 1) {
// if (null != res || (res instanceof String)) {
// //modify by shibb 模式解析
// System.out.print("自动解析"+"\n");
// //modify by shibb 模式解析
// System.out.print("自动解析"+"\n");
// obj = JQueryUtil.selectAnalyHtml(rule.getSelector().get("selector").split(","), document);
// ret.putAll(InfoAnalyUtil.getInforMation(obj.toString()));
// }
// System.out.print("自动解析"+"\n");
// System.out.print("自动解析"+"\n");
obj = JQueryUtil.selectAnalyHtml(rule.getSelector().get("selector").split(","), document);
ret.putAll(SellInfoUtil.getInforMation(obj.toString()));
} else {
@@ -125,7 +125,7 @@ public class Analyzer {
} else if (res != null && res instanceof String) {
String s = DataUtil.trim((String) res);
s = DataUtil.encoding(s).replaceAll("^\\?*|\\?*$", "").trim();
if (s.equals("暂无") || s.equals("暂无资料")) {
if (s.equals("暂无") || s.equals("暂无资料")) {
ret.put(rule.getField(), null);
} else {
ret.put(rule.getField(), s);
@@ -148,10 +148,10 @@ public class Analyzer {
/**
* 用选择器进行解析
* @param document 待解析文档(页面)
* @param rule 解析规则
* @return 解析后的数据
* 用选择器进行解析
* @param document 待解析文档(页面)
* @param rule 解析规则
* @return 解析后的数据
*/
private Object parseWithSelector(Document document, FieldRule rule) {
if (rule.getSelector() == null) {
@@ -181,7 +181,7 @@ public class Analyzer {
}
/**
* 根据数据库验证解析结果
* 根据数据库验证解析结果
*
* @param category
* @param city
@@ -191,27 +191,27 @@ public class Analyzer {
*/
public void validator(Map<String, Object> resultMap, String city, String category,List<FieldType> definedFields) throws Exception {
if (resultMap == null || resultMap.size() == 0) {
throw new Exception("对象为空");
throw new Exception("对象为空");
}
// 数据值类型转换
// 数据值类型转换
try {
castValueToFieldType(resultMap, definedFields);
} catch (Exception e) {
throw new Exception(e.toString());
}
// 是否缺失必要值
// 是否缺失必要值
List<FieldType> primaryFields = fieldTypeDao.findPrimaryFieldByCategory(category);
for (FieldType ft : primaryFields) {
if (StringUtils.isBlank((String) resultMap.get(ft.getName()))) {
throw new Exception(ft.getDisplay() + "(" + ft.getName() + ")错误");
throw new Exception(ft.getDisplay() + "(" + ft.getName() + ")错误");
}
}
}
/**
* 根据数据库验证解析结果
* 根据数据库验证解析结果
*
* @param resultMap
* @param city
@@ -221,30 +221,30 @@ public class Analyzer {
*/
public Map<String, Exception> validatorAll(Map<String, Object> resultMap, String city, String category) throws Exception {
if (resultMap == null || resultMap.size() == 0) {
throw new Exception("对象为空");
throw new Exception("对象为空");
}
List<FieldType> definedFields = fieldTypeDao.findByCategory(category);
// 数据值类型转换
// 数据值类型转换
Map<String, Exception> resultExceptionMap = castAllValueToFieldType(resultMap, definedFields);
if (resultExceptionMap == null) {
resultExceptionMap = new HashMap<String, Exception>();
}
// 是否缺失必要值
// 是否缺失必要值
List<FieldType> primaryFields = fieldTypeDao.findPrimaryFieldByCategory(category);
for (FieldType ft : primaryFields) {
if (StringUtils.isBlank((String) resultMap.get(ft.getName()))) {
resultMap.put(ft.getName(), null);
resultExceptionMap.put(ft.getName(), new Exception(ft.getDisplay() + "(" + ft.getName() + ")错误"));
resultExceptionMap.put(ft.getName(), new Exception(ft.getDisplay() + "(" + ft.getName() + ")错误"));
}
}
return resultExceptionMap;
}
/**
* 是否存在未定义字段
* 是否存在未定义字段
*
* @param resultObject
* @return
@@ -270,7 +270,7 @@ public class Analyzer {
/**
* 字段标准化
* 字段标准化
* @param resultMap
* @param city
* @param category
@@ -292,7 +292,7 @@ public class Analyzer {
try {
String value = String.valueOf(resultMap.get(ft.getName()));
if ("区域".equals(ft.getDisplay())) {
if ("区域".equals(ft.getDisplay())) {
String region = (String) resultMap.get("region");
String block = (String) resultMap.get("block");
if (region != null && regionBlockDao.isRegion(city, region)) {
@@ -306,55 +306,55 @@ public class Analyzer {
resultMap.put("region", regionBlockDao.formatRegion(city, region));
}
} else if ("建筑面积".equals(ft.getDisplay()) || "占地面积".equals(ft.getDisplay())) {
if (value.endsWith("万平方米")) {
} else if ("建筑面积".equals(ft.getDisplay()) || "占地面积".equals(ft.getDisplay())) {
if (value.endsWith("万平方米")) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")) * 10000);
} else if (value.endsWith("平方米") || value.endsWith("平") || value.endsWith("平米") || value.endsWith("㎡")) {
} else if (value.endsWith("平方米") || value.endsWith("平") || value.endsWith("平米") || value.endsWith("㎡")) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")));
} else if (value.endsWith("亩")) {
} else if (value.endsWith("亩")) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")) * 666);
} else if (value.endsWith("万")) {
} else if (value.endsWith("万")) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")) * 10000);
} else if (value.endsWith("平方公里") || value.endsWith("平方千米")) {
} else if (value.endsWith("平方公里") || value.endsWith("平方千米")) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")) * 1000);
}
} else if ("容积率".equals(ft.getDisplay()) || "绿化率".equals(ft.getDisplay())) {
} else if ("容积率".equals(ft.getDisplay()) || "绿化率".equals(ft.getDisplay())) {
try {
Double.parseDouble(value);
} catch (Exception e) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")));
}
} else if ("物业费".equals(ft.getDisplay())) {
} else if ("物业费".equals(ft.getDisplay())) {
try {
Double.parseDouble(value);
} catch (Exception e) {
resultMap.put(ft.getName(), Double.parseDouble(value.replaceAll("[^0-9\\.]", "")));
}
} else if ("开盘时间".equals(ft.getDisplay())) {
} else if ("开盘时间".equals(ft.getDisplay())) {
Date d = DateUtil.parseStringToDate(value);
if (d != null) {
resultMap.put(ft.getName(), DateUtil.formatToYYYYMMDD(d));
} else {
resultMap.remove(ft.getName());
}
} else if ("物业类型".equals(ft.getDisplay())) {
} else if ("物业类型".equals(ft.getDisplay())) {
if ("shop".equals(category)) {
if (StringUtils.indexOfAny(value, new String[] { "商业综合体", "城市综合体", "综合体" }) > -1) {
resultMap.put(ft.getName(), "商业综合体");
} else if (StringUtils.indexOfAny(value, new String[] { "百货", "百货商场", "购物中心" }) > -1) {
resultMap.put(ft.getName(), "百货购物中心商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商业街" }) > -1) {
resultMap.put(ft.getName(), "商业街商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "主题", "市场" }) > -1) {
resultMap.put(ft.getName(), "市场类商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "社区" }) > -1) {
resultMap.put(ft.getName(), "社区内铺");
} else if (StringUtils.indexOfAny(value, new String[] { "住宅底商", "裙楼" }) > -1) {
resultMap.put(ft.getName(), "住宅底商");
} else if (StringUtils.indexOfAny(value, new String[] { "商务", "酒店", "酒店", "旅游", "写字楼" }) > -1) {
resultMap.put(ft.getName(), "商务区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "交通设施", "地铁站", "火车站", "机场" }) > -1) {
resultMap.put(ft.getName(), "交通设施商铺");
if (StringUtils.indexOfAny(value, new String[] { "商业综合体", "城市综合体", "综合体" }) > -1) {
resultMap.put(ft.getName(), "商业综合体");
} else if (StringUtils.indexOfAny(value, new String[] { "百货", "百货商场", "购物中心" }) > -1) {
resultMap.put(ft.getName(), "百货购物中心商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商业街" }) > -1) {
resultMap.put(ft.getName(), "商业街商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "主题", "市场" }) > -1) {
resultMap.put(ft.getName(), "市场类商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "社区" }) > -1) {
resultMap.put(ft.getName(), "社区内铺");
} else if (StringUtils.indexOfAny(value, new String[] { "住宅底商", "裙楼" }) > -1) {
resultMap.put(ft.getName(), "住宅底商");
} else if (StringUtils.indexOfAny(value, new String[] { "商务", "酒店", "酒店", "旅游", "写字楼" }) > -1) {
resultMap.put(ft.getName(), "商务区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "交通设施", "地铁站", "火车站", "机场" }) > -1) {
resultMap.put(ft.getName(), "交通设施商铺");
}
}
}
@@ -370,7 +370,7 @@ public class Analyzer {
}
/**
* 把输入值转换成定义的类型,如果有转换异常,则按照字段名称存入MAP,如果MAP返回为空,说明这次值转换没有任何异常
* 把输入值转换成定义的类型,如果有转换异常,则按照字段名称存入MAP,如果MAP返回为空,说明这次值转换没有任何异常
*
* @param resultMap
* @param definedFields
@@ -447,7 +447,7 @@ public class Analyzer {
}
/**
* 把数值转换成定义的类型,一旦有转换异常发现,则立即抛出异常
* 把数值转换成定义的类型,一旦有转换异常发现,则立即抛出异常
*
* @param resultMap
* @param definedFields
@@ -538,7 +538,7 @@ public class Analyzer {
public void removeInvalidValueField(Map<String, Object> resultObject, String category) {
Set<String> removeKeys = new HashSet<String>();
for (String field : resultObject.keySet()) {
// 除了小区名称,其他的名称需要验证
// 除了小区名称,其他的名称需要验证
if ("name".equals(field)) {
continue;
}
@@ -103,7 +103,7 @@ public class AnalyzerConfig {
}
/**
* 是否把数据放入内存中
* 是否把数据放入内存中
*
* @return
*/
@@ -51,13 +51,13 @@ public class DistrictDiscoverer {
private Map<String,String> fieldTypeMap = new HashMap<String,String>();
// 数据对象的网站数量最低标准(数据入库)
// 数据对象的网站数量最低标准(数据入库)
public static final int FOUND_DATA_MIN_COUNT = 1;
// 数据对象的网站得分最低标准(数据入库)
// 数据对象的网站得分最低标准(数据入库)
public static final double FOUND_DATA_MIN_SCORE = 8.0;
// 字段有效的网站得分最低标准
// 字段有效的网站得分最低标准
public static final double FOUND_DATA_FIELD_MIN_SCORE = 6.0;
DistrictDiscoverer() {
@@ -69,11 +69,11 @@ public class DistrictDiscoverer {
}
public static void main(String[] args) {
new DistrictDiscoverer().discoverer("淮安", "district");
new DistrictDiscoverer().discoverer("淮安", "district");
}
/**
* 小区发现
* 小区发现
*
* @param city
* @param category
@@ -103,7 +103,7 @@ public class DistrictDiscoverer {
for (AnalySite analySite : analySites) {
String region = analySite.getRegion();
String name = analySite.getDistrictName();
// if(!analySite.getSiteNames().contains("搜房")){
// if(!analySite.getSiteNames().contains("搜房")){
// continue;
// }
@@ -130,7 +130,7 @@ public class DistrictDiscoverer {
continue;
}
// 是否有可信任的网站(8分或以上)
// 是否有可信任的网站(8分或以上)
// if (!validatorWebsite(city, category, analySite.getSiteNames().split(","))) {
// continue;
// }
@@ -160,7 +160,7 @@ public class DistrictDiscoverer {
if (newObj.get("estate_type2") != null) {
String estateType = (String) newObj.get("estate_type2");
if (StringUtils.indexOfAny(estateType, new String[] { "小区", "住宅", "商住", "别墅", "公寓", "洋房", "高层", "小高层", "洋楼" }) > -1) {
if (StringUtils.indexOfAny(estateType, new String[] { "小区", "住宅", "商住", "别墅", "公寓", "洋房", "高层", "小高层", "洋楼" }) > -1) {
districtDao.saveDistrict(newObj);
tc++;
}else{
@@ -179,15 +179,15 @@ public class DistrictDiscoverer {
}
}
System.out.println("区域非法未入库数量:"+illegalRegionCount);
System.out.println("区域非法未入库数量:"+illegalRegionCount);
for(String s:illegalRegions.keySet()){
System.out.println(" "+s+":"+illegalRegions.get(s));
}
System.out.println("地产类型非法未入库数量:"+illegalEstateTypeCount);
System.out.println("地产类型非法未入库数量:"+illegalEstateTypeCount);
for(String s:illegalEstateTypes.keySet()){
System.out.println(" "+s+":"+illegalEstateTypes.get(s));
}
System.out.println("地址不存在未入库数量:"+emptyCount);
System.out.println("地址不存在未入库数量:"+emptyCount);
System.out.println("tc:"+tc);
System.out.println("temp:"+temp);
}
@@ -365,7 +365,7 @@ public class DistrictDiscoverer {
}
/**
* 8分以上的网站可信任
* 8分以上的网站可信任
*
* @param siteNames
* @return
@@ -33,7 +33,7 @@ import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* 网页解析控制类
* 网页解析控制类
*
* @author xiaoyu
*
@@ -99,7 +99,7 @@ public class WebpageAnalyzer {
@SuppressWarnings("unchecked")
public void doAnalyzer(AnalyTask analyTask) {
//获取解析规则
//获取解析规则
List<FieldRule> fieldRuleList = getFieldRules(analyTask.getCategory(), analyTask.getCity(), analyTask.getSiteName(),
analyTask.getPageName());
if (fieldRuleList.size() == 0) {
@@ -112,24 +112,24 @@ public class WebpageAnalyzer {
analyTask.getSiteName(), analyTask.getPageName(), analyTask.getWebpageStatus());
int num=0;
//针对每一个抓取的页面
//针对每一个抓取的页面
for (String webpageId : webpageIdList) {
if (analyTaskDao.isStopped(analyTask.getId())) {
break;
}
//获取页面
//获取页面
Webpage webpage = webpageDao.findById(webpageId);
if (webpage == null || analyRoadDao.isExists(webpage.getUrl(), analyTask.getId())) {
continue;
}
// 原始URL
// 原始URL
String url = webpage.getUrl();
String city = webpage.getCity();
//类型 district,new_district,shop,office
//类型 district,new_district,shop,office
String category = webpage.getCategory();
// 是否有该数据类型
// 是否有该数据类型
DataType dataType = dataTypeDao.findByCategory(category);
if (dataType == null) {
continue;
@@ -141,14 +141,14 @@ public class WebpageAnalyzer {
try {
String anaMode = fieldRuleList.get(0).getAnaMode();
if (AnaMode.LIST.getMode().equals(anaMode)) {
//列表页解析
//列表页解析
List<Map<String, Object>> list = Analyzer.getInstance().analyListPage(webpage.getContent(), fieldRuleList);
int index = 0;
for(Map<String, Object> map : list) {
parseData(url.concat("#" + ++index), webpage, map, definedFields, primaryFields, dataType, analyTask);
}
}else {
//普通模式 AnaMode.COMMON
//普通模式 AnaMode.COMMON
Map<String, Object> map = Analyzer.getInstance().analy(webpage.getContent(), fieldRuleList);
parseData(url, webpage, map, definedFields, primaryFields, dataType, analyTask);
continue;
@@ -167,28 +167,28 @@ public class WebpageAnalyzer {
int valOpt = analyTask.getValueOptType();
int objOpt = analyTask.getObjectOptType();
//城市
//城市
String city = webpage.getCity();
//类型 district,new_district,shop,office
//类型 district,new_district,shop,office
String category = webpage.getCategory();
String webpageId = webpage.getId();
Map<String, Object> originalResultMap = new HashMap<String, Object>();
originalResultMap.put("city", city);
// 分析数据
// 分析数据
originalResultMap.putAll(anaResult);
// 是否有未定义字段
// 是否有未定义字段
String undefinedField = Analyzer.getInstance().getUndefinedField(definedFields, originalResultMap);
if (undefinedField != null) {
throw new Exception(undefinedField + "未定义");
throw new Exception(undefinedField + "未定义");
}
// 把字段标准化
// 把字段标准化
Analyzer.getInstance().formatToStandardValue(originalResultMap, city, analyTask.getCategory(), definedFields);
Map<String, Object> resultMap = new HashMap<String, Object>(originalResultMap);
// 删除无效字段
// 删除无效字段
Analyzer.getInstance().removeInvalidValueField(resultMap, analyTask.getCategory());
// 根据数据库规则验证字段
// 根据数据库规则验证字段
Analyzer.getInstance().validator(resultMap, city, analyTask.getCategory(),definedFields);
@@ -203,7 +203,7 @@ public class WebpageAnalyzer {
BasicDBObject newData = processUpdateData(primaryQuery, new BasicDBObject(resultMap), analyTask.getAnalyFields(),
dataType, valOpt, objOpt, analyTask.getId());
if (newData == null) {
throw new Exception("技术异常");
throw new Exception("技术异常");
}
if (newData.size() > 0) {
@@ -239,7 +239,7 @@ public class WebpageAnalyzer {
}*/
}
// 有值说明操作过数据库
// 有值说明操作过数据库
if (modifyData.size() > 0) {
analyTaskDao.increaseAnalyTaskEffectiveCount(analyTask.getId());
analyTaskDao.increaseEffectiveFieldsCount(analyTask.getId(), new ArrayList<String>(modifyData.keySet()));
@@ -274,10 +274,10 @@ public class WebpageAnalyzer {
}
/*private Map<String, Object> buildTypeFormat(Map<String, Object> resultMap, String cat) {
String[] types = {"多层","小高层","超高层","高层","花园洋房","老洋房","四合院","独栋","双拼","联排","叠加"};
String[] ptypes = {"多层","小高层","超高层","高层","花园洋房","老洋房","四合院"};
String[] btypes = {"独栋","双拼","联排","叠加"};
String[] stypes = {"多层","小高层","超高层","高层"};
String[] types = {"多层","小高层","超高层","高层","花园洋房","老洋房","四合院","独栋","双拼","联排","叠加"};
String[] ptypes = {"多层","小高层","超高层","高层","花园洋房","老洋房","四合院"};
String[] btypes = {"独栋","双拼","联排","叠加"};
String[] stypes = {"多层","小高层","超高层","高层"};
String build_type = "";
String estate = "";
@@ -300,31 +300,31 @@ public class WebpageAnalyzer {
build=build_type.split(",");
}else if(build_type.indexOf(";")!=-1){
build=build_type.split(";");
}else if(build_type.indexOf("、")!=-1){
build=build_type.split("、");
}else if(build_type.indexOf("、")!=-1){
build=build_type.split("、");
}else if(build_type.indexOf("/")!=-1){
build=build_type.split("/");
}else if(build_type.indexOf(",")!=-1){
build=build_type.split(",");
}else if(build_type.indexOf(",")!=-1){
build=build_type.split(",");
}else{
build=build_type.split("\\s+");
}
if(build.length>1){
for(int i=0;i<build.length;i++){
if("普通住宅".equals(estate)){
if("普通住宅".equals(estate)){
for(String ptype:ptypes){
if(ptype.equals(build[i])){
String s=build[i];
set.add(build[i]);
}
}
}else if("别墅".equals(estate)){
}else if("别墅".equals(estate)){
for(String ptype:btypes){
if(ptype.equals(build[i])){
set.add(build[i]);
}
}
}else if("商住".equals(estate)){
}else if("商住".equals(estate)){
for(String ptype:stypes){
if(ptype.equals(build[i])){
set.add(build[i]);
@@ -333,11 +333,11 @@ public class WebpageAnalyzer {
}
}
if(set.isEmpty()){
if("别墅".equals(estate)){
mbuild="联排";
if("别墅".equals(estate)){
mbuild="联排";
resultMap.put("build_type", mbuild);
}else{
mbuild="小高层";
mbuild="小高层";
resultMap.put("build_type", mbuild);
}
} else {
@@ -357,21 +357,21 @@ public class WebpageAnalyzer {
}
if(flag == false){
if("别墅".equals(estate)){
mbuild="联排";
if("别墅".equals(estate)){
mbuild="联排";
resultMap.put("build_type", mbuild);
}else{
mbuild="小高层";
mbuild="小高层";
resultMap.put("build_type", mbuild);
}
}
}
} else {
if("别墅".equals(estate)){
mbuild="联排";
if("别墅".equals(estate)){
mbuild="联排";
resultMap.put("build_type", mbuild);
}else{
mbuild="小高层";
mbuild="小高层";
resultMap.put("build_type", mbuild);
}
}
@@ -399,49 +399,49 @@ public class WebpageAnalyzer {
if(resultMap.get("estate_type2") != null){
value = resultMap.get("estate_type2").toString().trim();
} else {
resultMap.put("estate_type2", "社区商铺");
resultMap.put("estate_type2", "社区商铺");
}
if (StringUtils.indexOfAny(value, new String[] { "商业综合体", "城市综合体", "综合体" , "商业广场" }) > -1) {
resultMap.put("estate_type2", "商业综合体");
} else if (StringUtils.indexOfAny(value, new String[] { "百货", "百货商场", "购物中心" }) > -1) {
resultMap.put("estate_type2", "百货购物中心商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商业街" , "产权式商铺" }) > -1) {
resultMap.put("estate_type2", "商业街商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "主题", "市场" }) > -1) {
resultMap.put("estate_type2", "市场类商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "社区" , "住宅底商", "裙楼" , "住宅"}) > -1) {
resultMap.put("estate_type2", "社区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商务", "酒店", "酒店", "旅游", "写字楼" , "旅游" , "甲级" , "创意园区" , "办公"}) > -1) {
resultMap.put("estate_type2", "商务区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "交通设施", "地铁站", "火车站", "机场" }) > -1) {
resultMap.put("estate_type2", "交通设施商铺");
if (StringUtils.indexOfAny(value, new String[] { "商业综合体", "城市综合体", "综合体" , "商业广场" }) > -1) {
resultMap.put("estate_type2", "商业综合体");
} else if (StringUtils.indexOfAny(value, new String[] { "百货", "百货商场", "购物中心" }) > -1) {
resultMap.put("estate_type2", "百货购物中心商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商业街" , "产权式商铺" }) > -1) {
resultMap.put("estate_type2", "商业街商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "主题", "市场" }) > -1) {
resultMap.put("estate_type2", "市场类商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "社区" , "住宅底商", "裙楼" , "住宅"}) > -1) {
resultMap.put("estate_type2", "社区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "商务", "酒店", "酒店", "旅游", "写字楼" , "旅游" , "甲级" , "创意园区" , "办公"}) > -1) {
resultMap.put("estate_type2", "商务区商铺");
} else if (StringUtils.indexOfAny(value, new String[] { "交通设施", "地铁站", "火车站", "机场" }) > -1) {
resultMap.put("estate_type2", "交通设施商铺");
} else {
resultMap.put("estate_type2", "社区商铺");
resultMap.put("estate_type2", "社区商铺");
}
return resultMap;
}
private Map<String, Object> officeEstateType(Map<String, Object> resultMap) {
String[] bTypes={"写字楼","标准写字楼","甲级","标准写字楼","纯写字楼","乙级","涵盖写字楼","摩天商务","5A级","独栋总部大楼","甲级办公","办公","高端写字间"};
String[] sTypes={"公寓","商住公寓","商务公寓","住宅","商住楼","住宅","商业综合体","loft","商住两用楼","大型商业"};
String[] mTypes={"大型商业","建筑综合体","商务中心","商业综合体","综合体","大型商业综合体","大型高端城市综合体"};
String[] hTypes={"酒店写字楼","酒店及商业","星际公寓","星空会所","酒店式公寓","酒店","星级酒店"};
String[] yTypes={"创意园区","总部园区","总部园区","创意"};
String[] bTypes={"写字楼","标准写字楼","甲级","标准写字楼","纯写字楼","乙级","涵盖写字楼","摩天商务","5A级","独栋总部大楼","甲级办公","办公","高端写字间"};
String[] sTypes={"公寓","商住公寓","商务公寓","住宅","商住楼","住宅","商业综合体","loft","商住两用楼","大型商业"};
String[] mTypes={"大型商业","建筑综合体","商务中心","商业综合体","综合体","大型商业综合体","大型高端城市综合体"};
String[] hTypes={"酒店写字楼","酒店及商业","星际公寓","星空会所","酒店式公寓","酒店","星级酒店"};
String[] yTypes={"创意园区","总部园区","总部园区","创意"};
String name = resultMap.get("name").toString().trim();
String estate_type2 = "";
if(resultMap.get("estate_type2") != null){
estate_type2 = resultMap.get("estate_type2").toString().trim();
} else {
resultMap.put("estate_type2", "标准写字楼");
resultMap.put("estate_type2", "标准写字楼");
}
boolean flag=false;
if(StringUtils.isNotBlank(estate_type2)){
String[] types = {"标准写字楼","商住两用楼 ","商业综合楼","酒店商务楼","园区写字楼"};
String[] types = {"标准写字楼","商住两用楼 ","商业综合楼","酒店商务楼","园区写字楼"};
for(String type:types){
if(estate_type2.indexOf(type)!=-1){
estate_type2=type;
@@ -452,53 +452,53 @@ public class WebpageAnalyzer {
if(flag==false){
for(String type:bTypes){
if(estate_type2.indexOf(type)!=-1){
resultMap.put("estate_type2", "标准写字楼");
estate_type2 = "标准写字楼";
resultMap.put("estate_type2", "标准写字楼");
estate_type2 = "标准写字楼";
flag=true;
}
}
for(String type:sTypes){
if(estate_type2.indexOf(type)!=-1){
resultMap.put("estate_type2", "商住两用楼");
estate_type2 = "商住两用楼";
resultMap.put("estate_type2", "商住两用楼");
estate_type2 = "商住两用楼";
flag=true;
}
}
for(String type:mTypes){
if(estate_type2.indexOf(type)!=-1){
resultMap.put("estate_type2", "商业综合楼");
estate_type2 = "商业综合楼";
resultMap.put("estate_type2", "商业综合楼");
estate_type2 = "商业综合楼";
flag=true;
}
}
for(String type:hTypes){
if(estate_type2.indexOf(type)!=-1){
resultMap.put("estate_type2", "酒店商务楼");
estate_type2 = "酒店商务楼";
resultMap.put("estate_type2", "酒店商务楼");
estate_type2 = "酒店商务楼";
flag=true;
}
}
for(String type:yTypes){
if(estate_type2.indexOf(type)!=-1){
resultMap.put("estate_type2", "园区写字楼");
estate_type2 = "园区写字楼";
resultMap.put("estate_type2", "园区写字楼");
estate_type2 = "园区写字楼";
flag=true;
}
}
if(flag==false){
resultMap.put("estate_type2", "标准写字楼");
resultMap.put("estate_type2", "标准写字楼");
}
}
} else {
resultMap.put("estate_type2", "标准写字楼");
resultMap.put("estate_type2", "标准写字楼");
}
return resultMap;
}
private Map<String, Object> districtEstateType(Map<String, Object> resultMap) {
String[] types = {"普通住宅","别墅","商住"};
String[] types = {"普通住宅","别墅","商住"};
String name = resultMap.get("name").toString().trim();
boolean flag=false;
@@ -514,17 +514,17 @@ public class WebpageAnalyzer {
}
}
if(flag == false){
if(name.indexOf("别墅") != -1){
resultMap.put("estate_type2", "别墅");
if(name.indexOf("别墅") != -1){
resultMap.put("estate_type2", "别墅");
}else {
resultMap.put("estate_type2", "普通住宅");
resultMap.put("estate_type2", "普通住宅");
}
}
} else {
if(name.indexOf("别墅") != -1){
resultMap.put("estate_type2", "别墅");
if(name.indexOf("别墅") != -1){
resultMap.put("estate_type2", "别墅");
}else {
resultMap.put("estate_type2", "普通住宅");
resultMap.put("estate_type2", "普通住宅");
}
}
return resultMap;
@@ -552,11 +552,11 @@ public class WebpageAnalyzer {
if (dbObject != null) {
for (String f : resultObject.keySet()) {
if (valueOptType == 0) {// 空值补充
if (valueOptType == 0) {// 空值补充
if (dbObject.get(f) == null || StringUtils.isBlank(String.valueOf(dbObject.get(f)))) {
newObject.put(f, resultObject.get(f));
}
} else if (valueOptType == 1) {// 强制信任
} else if (valueOptType == 1) {// 强制信任
Map<String, Object> markMap = (Map<String, Object>) dbObject.get("mark_map");
if (markMap == null || markMap.size() == 0) {
newObject.put(f, resultObject.get(f));
@@ -565,9 +565,9 @@ public class WebpageAnalyzer {
newObject.put(f, resultObject.get(f));
}
}
} else if (valueOptType == 2) {// 强制替换
} else if (valueOptType == 2) {// 强制替换
newObject.put(f, resultObject.get(f));
} else if (valueOptType == 3){// 不做更新
} else if (valueOptType == 3){// 不做更新
}
}
@@ -1,12 +1,12 @@
package com.fangjia.coredata.webdata.e;
/**
* ½âÎöģʽ
* 解析模式
* Created by linxiaoshuai on 2016/4/6.
*/
public enum AnaMode {
COMMON("common", "ÆÕͨģʽ"),
LIST("list", "Áбíģʽ");
COMMON("common", "普通模式"),
LIST("list", "列表模式");
private String mode;
private String desc;
@@ -87,7 +87,7 @@ public class DynamicWebpageAnalyzer {
/**
* 数据解析
* 数据解析
*
* @param collector
* @param executor
@@ -117,13 +117,13 @@ public class DynamicWebpageAnalyzer {
executor.invoke(page);
} catch (InterruptedException ex) {
LOG.info("opt:异常\tcat:" + page.getCategory() + "\tjob:" + page.getMetadata().getJobId() + "\tcode:-\turl:" + page.getMetadata().getUrl() + "\textra_data:" + extraData.toString() + "\texception:" + page.getMetadata().getId() + " " + ex.toString());
loggerToMongo("异常", page.getCategory(), page.getMetadata().getJobId(), page.getMetadata().getSessionId(), -1, page.getMetadata().getUrl(), page.getMetadata().getReferer(), extraData, ex.toString());
LOG.info("opt:异常\tcat:" + page.getCategory() + "\tjob:" + page.getMetadata().getJobId() + "\tcode:-\turl:" + page.getMetadata().getUrl() + "\textra_data:" + extraData.toString() + "\texception:" + page.getMetadata().getId() + " " + ex.toString());
loggerToMongo("异常", page.getCategory(), page.getMetadata().getJobId(), page.getMetadata().getSessionId(), -1, page.getMetadata().getUrl(), page.getMetadata().getReferer(), extraData, ex.toString());
putToMetaQueue(page.getMetadata().getId());
saveToSnapshotDB(page, ex.toString());
} catch (Exception ex) {
LOG.info("opt:异常\tcat:" + page.getCategory() + "\tjob:" + page.getMetadata().getJobId() + "\tcode:-\turl:" + page.getMetadata().getUrl() + "\textra_data:" + extraData.toString() + "\texception:" + page.getMetadata().getId() + " " + ex.toString());
loggerToMongo("异常", page.getCategory(), page.getMetadata().getJobId(), page.getMetadata().getSessionId(), -1, page.getMetadata().getUrl(), page.getMetadata().getReferer(), extraData, ex.toString());
LOG.info("opt:异常\tcat:" + page.getCategory() + "\tjob:" + page.getMetadata().getJobId() + "\tcode:-\turl:" + page.getMetadata().getUrl() + "\textra_data:" + extraData.toString() + "\texception:" + page.getMetadata().getId() + " " + ex.toString());
loggerToMongo("异常", page.getCategory(), page.getMetadata().getJobId(), page.getMetadata().getSessionId(), -1, page.getMetadata().getUrl(), page.getMetadata().getReferer(), extraData, ex.toString());
putToMetaQueue(page.getMetadata().getId());
saveToSnapshotDB(page, ex.toString());
}
@@ -137,7 +137,7 @@ public class DynamicWebpageAnalyzer {
}
/**
* 保存到临时的快照库,方便排错
* 保存到临时的快照库,方便排错
* @param page
*/
private void saveToSnapshotDB(Page page, String reason) {
@@ -167,7 +167,7 @@ public class DynamicWebpageAnalyzer {
}
/**
* 数据发布
* 数据发布
*/
public void doPublish(final Executor<Page, Result> executor) {
for(int i=0;i < 20;i++) {
@@ -200,7 +200,7 @@ public class DynamicWebpageAnalyzer {
}
/**
* 删除metadata
* 删除metadata
*/
public void doDeleteMetadata() {
Thread publishThread = new Thread(new Runnable() {
@@ -261,11 +261,11 @@ public class DynamicWebpageAnalyzer {
if (seabirdEntity != null) {
if (seabirdEntity.getPublishDate().before((Date) resultMap.get("publish_date"))) {
seabirdDao.updateById(new BasicDBObject(resultMap), seabirdEntity.getId());
LOG.info("opt:更新\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("更新", category, jobId, sessionId, code, url, referer, extraData);
LOG.info("opt:更新\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("更新", category, jobId, sessionId, code, url, referer, extraData);
} else {
LOG.info("opt:放弃\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("放弃", category, jobId, sessionId, code, url, referer, extraData);
LOG.info("opt:放弃\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("放弃", category, jobId, sessionId, code, url, referer, extraData);
saveToSnapshotDB(page, "");
}
doCappedLogger((String)extraData.get("city"), (String)extraData.get("site_name"), (String)extraData.get("page_name"), category, jobId);
@@ -274,12 +274,12 @@ public class DynamicWebpageAnalyzer {
seabirdDao.save(obj);
saveToDatabackup(obj);
doCappedLogger((String) extraData.get("city"), (String) extraData.get("site_name"), (String) extraData.get("page_name"), category, jobId);
LOG.info("opt:保存\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("保存", category, jobId, sessionId, code, url, referer, extraData);
LOG.info("opt:保存\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("保存", category, jobId, sessionId, code, url, referer, extraData);
}
} else {
LOG.info("opt:过滤\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("过滤", category, jobId, sessionId, code, url, referer, extraData);
LOG.info("opt:过滤\tcat:" + category + "\tjob:" + jobId + "\tcode:" + code + "\turl:" + url + "\textra_data:" + extraData.toString());
loggerToMongo("过滤", category, jobId, sessionId, code, url, referer, extraData);
saveToSnapshotDB(page, "");
}
}
@@ -306,7 +306,7 @@ public class DynamicWebpageAnalyzer {
}
private void loggerToMongo(String opt, String cat, String jobId, String sessionId, int code, String url, String referer, Map<String, Object> extraMap) {
loggerToMongo("过滤", cat, jobId, sessionId, code, url, referer, extraMap, null);
loggerToMongo("过滤", cat, jobId, sessionId, code, url, referer, extraMap, null);
}
private void loggerToMongo(String opt, String cat, String jobId, String sessionId, int code, String url, String referer, Map<String, Object> extraMap, String exceptions) {
@@ -380,42 +380,42 @@ public class DynamicWebpageAnalyzer {
return 1;
}
//区域
//区域
if (StringUtils.isBlank((String) object.get("region"))) {
return 3;
}
//总价不存在
//总价不存在
if (object.get("total_price") == null) {
return 6;
}
//标题不存在
//标题不存在
if (object.get("name") == null || StringUtils.isBlank((String) object.get("name"))) {
return 13;
}
//发布日期不存在
//发布日期不存在
if (object.get("publish_date") == null) {
return 7;
}
if("sell".equals(object.get("cat")) || "rent".equals(object.get("cat"))){
//小区名
//小区名
if (StringUtils.isBlank((String) object.get("district_name"))) {
return 4;
}
if ("rent".equals(object.get("cat"))) {
//面积不存在
//面积不存在
if (object.get("area") == null && (object.get("room") == null || (Integer) object.get("room") <= 0 || (Integer) object.get("room") > 10)) {
return 15;
}
if (object.get("estate_type") != null) {
String estate_type = (String) object.get("estate_type");
if (estate_type.indexOf("写字楼")!=-1||estate_type.indexOf("商铺")!=-1) {
if (estate_type.indexOf("写字楼")!=-1||estate_type.indexOf("商铺")!=-1) {
return 8;
}
}
@@ -425,12 +425,12 @@ public class DynamicWebpageAnalyzer {
// }
} else if ("sell".equals(object.get("cat"))) {
//面积不存在
//面积不存在
if (object.get("area") == null) {
return 5;
}
//面积大小不在规定范围内
//面积大小不在规定范围内
try {
if (object.get("area") instanceof String) {
if (Double.parseDouble((String) object.get("area")) < 10
@@ -446,7 +446,7 @@ public class DynamicWebpageAnalyzer {
}
//价格不在规定的区间内
//价格不在规定的区间内
if ((Integer) object.get("total_price") <= 50000) {
return 12;
}
@@ -479,10 +479,10 @@ public class DynamicWebpageAnalyzer {
/**
* 定时打印处理速度
* 定时打印处理速度
*/
private static void calculateSpeed(final Collector<Page> collector, final Executor<Page, Result> executor) {
//打印日志时间间隔(单位:秒)
//打印日志时间间隔(单位:秒)
final int gapSecs = 10;
Timer timer = new Timer("counter");
timer.scheduleAtFixedRate(new TimerTask() {
@@ -495,10 +495,10 @@ public class DynamicWebpageAnalyzer {
}
/**
* 定时清理快照中的数据,默认只保存一周的数据,删除昨天以前的
* 定时清理快照中的数据,默认只保存一周的数据,删除昨天以前的
*/
private void monitorSnapshot() {
//扫描快照间隔时间(单位:小时)
//扫描快照间隔时间(单位:小时)
final int gapHours = 12;
Timer timer = new Timer("snapshotScanner");
timer.scheduleAtFixedRate(new TimerTask() {
@@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* 待处理网页收集器
* 待处理网页收集器
* Created by dxy on 2015/7/23.
*/
@@ -146,22 +146,22 @@ public class PageCollector implements Collector<Page> {
jedis.close();
}
if(metadatas.size() > 0){
LOGGER.error("[Redis] job:" + job.getJobId() + ", 获取数据量:" + metadatas.size() + " ,耗时:" + (System.currentTimeMillis() - start));
LOGGER.error("[Redis] job:" + job.getJobId() + ", 获取数据量:" + metadatas.size() + " ,耗时:" + (System.currentTimeMillis() - start));
return metadatas.size();
}
//这个任务在metadata库中的数据量为0
//这个任务在metadata库中的数据量为0
if(JOB_METADATA_COUNT_MAP.get(job.getJobId()) == 0) {
return 0;
}
LOGGER.error("查找Metadata:" + DateUtil.formatToTightYYYYMMDDhhmmss(new Date()));
//为了避免重复收集metadata数据,所以利用c_date进行分时间段提取
LOGGER.error("查找Metadata:" + DateUtil.formatToTightYYYYMMDDhhmmss(new Date()));
//为了避免重复收集metadata数据,所以利用c_date进行分时间段提取
if (!JOB_EARLIEST_DATE.containsKey(job.getJobId())) {
Date earliestDate = metadataDao.findEarliestMetadata(job.getJobId());
if (earliestDate == null) {
return 0;
}
//减去1毫秒,确保最早的一条数据可以被查询到
//减去1毫秒,确保最早的一条数据可以被查询到
JOB_EARLIEST_DATE.put(job.getJobId(), new Date(earliestDate.getTime() - 1));
}
@@ -176,7 +176,7 @@ public class PageCollector implements Collector<Page> {
int metaDataCount = JOB_METADATA_COUNT_MAP.get(job.getJobId());
if(metaDataCount < 1000){
metadatas = metadataDao.findMetadataByJobId(job.getJobId(), null, metaDataCount);
}else if(RandomUtils.nextInt(2) == 1){//50%的概率会处理数量较少的任务
}else if(RandomUtils.nextInt(2) == 1){//50%的概率会处理数量较少的任务
metadatas = metadataDao.findMetadataByJobId(job.getJobId(), null, BATCH_LIMIT);
}else{
return 0;
@@ -188,7 +188,7 @@ public class PageCollector implements Collector<Page> {
return 0;
}
//重复动作,按时间正序(数据库中已进行asc=true的排序)
//重复动作,按时间正序(数据库中已进行asc=true的排序)
Collections.sort(metadatas, new Comparator<Metadata>() {
@Override
public int compare(Metadata o1, Metadata o2) {
@@ -211,7 +211,7 @@ public class PageCollector implements Collector<Page> {
JOB_EARLIEST_DATE.put(job.getJobId(), earliestDate);
}
}
LOGGER.error("job:" + job.getJobId() + ", 获取数据量:" + metadatas.size() + " ,耗时:" + (System.currentTimeMillis() - start));
LOGGER.error("job:" + job.getJobId() + ", 获取数据量:" + metadatas.size() + " ,耗时:" + (System.currentTimeMillis() - start));
return metadatas.size();
}
@@ -64,7 +64,7 @@ public class PageExecutor implements Executor<Page, Result> {
List<FieldRule> fieldRules = fieldRuleContainer.getPageFieldRule(category, page.getSiteName(), page.getPageName());
if(fieldRules == null || fieldRules.size() == 0) {
throw new Exception("category:" + page.getCategory() + ",siteName:" + page.getSiteName() + ",pageName:" + page.getPageName() + ":无解析规则");
throw new Exception("category:" + page.getCategory() + ",siteName:" + page.getSiteName() + ",pageName:" + page.getPageName() + ":无解析规则");
}
String url = metadata.getUrl();
@@ -76,18 +76,18 @@ public class PageExecutor implements Executor<Page, Result> {
Map<String, Object> originalResultMap = new HashMap<String, Object>();
originalResultMap.put("city", city);
// 分析数据
// 分析数据
originalResultMap.putAll(Analyzer.getInstance().analy(content, fieldRules));
// 是否有未定义字段
// 是否有未定义字段
String undefinedField = Analyzer.getInstance().getUndefinedField(definedFields, originalResultMap);
if (undefinedField != null) {
throw new Exception(undefinedField + "未定义");
throw new Exception(undefinedField + "未定义");
}
// 把字段标准化
// 把字段标准化
Analyzer.getInstance().formatToStandardValue(originalResultMap, city, category, definedFields);
Map<String, Object> resultMap = new HashMap<String, Object>(originalResultMap);
// 根据数据库规则验证字段
// 根据数据库规则验证字段
Analyzer.getInstance().validator(resultMap, city, category, definedFields);
DBObject primaryQuery = new BasicDBObject();