zoukankan      html  css  js  c++  java
  • 微博excel数据清洗(Java版)

    微博数据清洗(Java版)

    原创 2013年12月10日 10:58:24

    大数据公益大学提供的一份数据,义务处理一下,原始数据是Excel,含有html标签,如下:

     

    要求清洗掉html标签,和微博内容中的url地址。

    主要分为两部分:

    1.处理文本,清洗数据。

    2.处理excel读写操作。

    上代码:

    ExcelUtil类,包含Excel2003-2007的读写操作,Excel使用Apache POI进行操作,需要jar包如下:


    [java] view plain copy
     
    1. package dat.datadeal;  
    2.   
    3. import java.io.File;  
    4. import java.io.FileInputStream;  
    5. import java.io.FileNotFoundException;  
    6. import java.io.FileOutputStream;  
    7. import java.io.IOException;  
    8. import java.io.InputStream;  
    9. import java.text.ParseException;  
    10. import java.text.SimpleDateFormat;  
    11. import java.util.ArrayList;  
    12. import java.util.Date;  
    13. import java.util.List;  
    14. import java.util.Locale;  
    15. import java.util.logging.Level;  
    16. import java.util.logging.Logger;  
    17.   
    18. import org.apache.poi.hssf.usermodel.HSSFCell;  
    19. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
    20. import org.apache.poi.hssf.usermodel.HSSFRow;  
    21. import org.apache.poi.hssf.usermodel.HSSFSheet;  
    22. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    23. import org.apache.poi.ss.usermodel.Cell;  
    24. import org.apache.poi.ss.usermodel.DateUtil;  
    25. import org.apache.poi.ss.usermodel.Row;  
    26. import org.apache.poi.ss.usermodel.Sheet;  
    27. import org.apache.poi.ss.usermodel.Workbook;  
    28. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
    29.   
    30. /** 
    31.  *  
    32.  * @author daT dev.tao@gmail.com 
    33.  *2003,2007版excel读写工具 
    34.  */  
    35. public class ExcelUtil{  
    36.       
    37.     /** 
    38.      * Excel文件读取 
    39.      * @param filePath 
    40.      * @return String[]存的是行,List存的是列。 
    41.      * 一个excel一次全部读入内存(Excel超大需要另行处理) 
    42.      */  
    43.     public  List<String[]> readExcel(String filePath) {    
    44.         List<String[]> dataList = new ArrayList<String[]>();    
    45.         boolean isExcel2003 = true;    
    46.         if (isExcel2007(filePath)) {    
    47.             isExcel2003 = false;    
    48.         }    
    49.         File file = new File(filePath);    
    50.         InputStream is = null;    
    51.         try {    
    52.             is = new FileInputStream(file);    
    53.         } catch (FileNotFoundException ex) {    
    54.             Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);    
    55.         }    
    56.         Workbook wb = null;    
    57.         try {    
    58.             wb = isExcel2003 ? new HSSFWorkbook(is) : new XSSFWorkbook(is);    
    59.         } catch (IOException ex) {    
    60.             Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);    
    61.         }    
    62.         Sheet sheet = wb.getSheetAt(0);    
    63.         int totalRows = sheet.getPhysicalNumberOfRows();    
    64.         int totalCells = 0;    
    65.         if (totalRows >= 1 && sheet.getRow(0) != null) {    
    66.             totalCells = sheet.getRow(0).getPhysicalNumberOfCells();    
    67.         }    
    68.         for (int r = 0; r < totalRows; r++) {    
    69.             Row row = sheet.getRow(r);    
    70.             if (row == null) {    
    71.                 continue;    
    72.             }    
    73.             String[] rowList = new String[totalCells];    
    74.             for (int c = 0; c < totalCells; c++) {    
    75.                 Cell cell = row.getCell(c);    
    76.                 String cellValue = "";    
    77.                 if (cell == null) {    
    78.                     rowList[c] = (cellValue);    
    79.                     continue;    
    80.                 }    
    81.                 cellValue = ConvertCellStr(cell, cellValue);    
    82.                 rowList[c] = (cellValue);    
    83.             }    
    84.             dataList.add(rowList);    
    85.         }    
    86.         return dataList;    
    87.     }    
    88.       
    89.       
    90.     private String ConvertCellStr(Cell cell, String cellStr) {    
    91.         switch (cell.getCellType()) {    
    92.             case Cell.CELL_TYPE_STRING:    
    93.                 // 读取String    
    94.                 cellStr = cell.getStringCellValue().toString();    
    95.                 break;    
    96.             case Cell.CELL_TYPE_BOOLEAN:    
    97.                 // 得到Boolean对象的方法    
    98.                 cellStr = String.valueOf(cell.getBooleanCellValue());    
    99.                 break;    
    100.             case Cell.CELL_TYPE_NUMERIC:    
    101.                 // 先看是否是日期格式    
    102.                 if (DateUtil.isCellDateFormatted(cell)) {    
    103.                     // 读取日期格式    
    104.                     cellStr = formatTime(cell.getDateCellValue().toString());    
    105.                 } else {    
    106.                     // 读取数字    
    107.                     cellStr = String.valueOf(cell.getNumericCellValue());    
    108.                 }    
    109.                 break;    
    110.             case Cell.CELL_TYPE_FORMULA:    
    111.                 // 读取公式    
    112.                 cellStr = cell.getCellFormula().toString();    
    113.                 break;    
    114.         }    
    115.         return cellStr;    
    116.     }    
    117.     
    118.   
    119.   
    120.     private boolean isExcel2007(String fileName) {    
    121.             return fileName.matches("^.+\.(?i)(xlsx)$");    
    122.      }   
    123.        
    124.     private String formatTime(String s) {    
    125.         SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.ENGLISH);    
    126.         Date date = null;    
    127.         try {    
    128.             date = sf.parse(s);    
    129.         } catch (ParseException ex) {    
    130.             Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);    
    131.         }    
    132.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
    133.         String result = sdf.format(date);    
    134.         return result;    
    135.     }    
    136.        
    137.       
    138.     /** 
    139.      * Excel写操作,简单起见还是采用内存数据一次写入 
    140.      * @param filePath 输出文件路径名 
    141.      * @param dataList 输出文件内容,List<String>行  List列 
    142.      * @throws IOException 
    143.      */  
    144.     public  void writeExcel(String filePath,List<List<String>> dataList) throws IOException{  
    145.             HSSFWorkbook wb = new HSSFWorkbook();    
    146.             HSSFSheet sheet = wb.createSheet("sheet");// 添加sheet    
    147.             // 表格样式    
    148.             HSSFCellStyle style = wb.createCellStyle();    
    149.             style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 指定单元格居中对齐    
    150.             // // 边框    
    151.             // style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);    
    152.             // style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);    
    153.             // style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);    
    154.             // style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);    
    155.             // //设置字体    
    156.             // HSSFFont f = wb.createFont();    
    157.             // f.setFontHeightInPoints((short)10);    
    158.             // f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);    
    159.             // style.setFont(f);    
    160.             // //设置列宽    
    161.             // sheet.setColumnWidth((short)0, (short)9600);    
    162.             // sheet.setColumnWidth((short)1, (short)4000);    
    163.             // sheet.setColumnWidth((short)2, (short)8000);    
    164.             // sheet.setColumnWidth((short)3, (short)8000);    
    165.         
    166.             // 在索引0的位置创建第一行    
    167.         
    168.             for (int i = 0; i < dataList.size(); i++) {    
    169.                 HSSFRow row = sheet.createRow(i);    
    170.                 List<String> list = dataList.get(i);    
    171.                 for (int j = 0; j < list.size(); j++) {    
    172.                     HSSFCell cell = row.createCell(j);    
    173.                     cell.setCellValue(list.get(j));    
    174.                     cell.setCellStyle(style);    
    175.                 }    
    176.             }    
    177.             // 导出文件    
    178.             FileOutputStream fout = new FileOutputStream(filePath);    
    179.             wb.write(fout);    
    180.             fout.close();    
    181.     }  
    182.       
    183. }  

    DataClean类,包含对html标签,信息中url的的清洗。
    [java] view plain copy
     
    1. package dat.datadeal;  
    2.   
    3. import java.io.IOException;  
    4. import java.util.ArrayList;  
    5. import java.util.List;  
    6. import java.util.regex.Matcher;  
    7. import java.util.regex.Pattern;  
    8.   
    9. /** 
    10.  *  
    11.  * @author daT dev.tao@gmail.com 
    12.  * 
    13.  */  
    14. public class DataClean {  
    15.       
    16.     /** 
    17.      * 清洗html标签 
    18.      * @param inputString 
    19.      * @return 
    20.      */  
    21.     public static String delHtml(String inputString) {  
    22.         String htmlStr = inputString; // 含html标签的字符串  
    23.         String textStr = "";  
    24.         java.util.regex.Pattern p_script;  
    25.         java.util.regex.Matcher m_script;  
    26.         java.util.regex.Pattern p_html;  
    27.         java.util.regex.Matcher m_html;  
    28.         try {  
    29.             String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式  
    30.             String regEx_script = "<[/s]*?script[^>]*?>[/s/S]*?<[/s]*?//[/s]*?script[/s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[/s/S]*?<//script>  
    31.             p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
    32.             m_script = p_script.matcher(htmlStr);  
    33.             htmlStr = m_script.replaceAll(""); // 过滤script标签  
    34.             p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
    35.             m_html = p_html.matcher(htmlStr);  
    36.             htmlStr = m_html.replaceAll(""); // 过滤html标签  
    37.             textStr = htmlStr;  
    38.         } catch (Exception e) {  
    39.             System.err.println("Html2Text: " + e.getMessage());  
    40.         }  
    41.         return textStr;// 返回文本字符串  
    42.     }  
    43.       
    44.     /** 
    45.      * 处理掉信息中的url地址 
    46.      */  
    47.     public static String dealWithUrl(String str){  
    48.         String regEx = "[http|https]+[://]+[0-9A-Za-z:/[-]_#[?][=][.][&]]*";  
    49.         Pattern p = Pattern.compile(regEx);     
    50.         Matcher m = p.matcher(str);  
    51.         return m.replaceAll("");  
    52.     }  
    53.       
    54.       
    55.     public static void main(String[] args) throws IOException{  
    56.         ExcelUtil excelUtil = new ExcelUtil();  
    57.         List<List<String>> writeList = new ArrayList<List<String>>();  
    58.         List<String[]> readList =excelUtil.readExcel("/home/dat/javatest/微博数据_.xlsx");  
    59.         for(String[] lineArray:readList){  
    60.             List<String> strList = new ArrayList<String>();  
    61.             for(String str:lineArray){  
    62.                 String strTmp = DataClean.dealWithUrl(DataClean.delHtml(str));  
    63.                 strList.add(strTmp);  
    64.                 //System.out.println(strTmp);  
    65.             }  
    66.             writeList.add(strList);  
    67.         }  
    68.           
    69.         excelUtil.writeExcel("/home/dat/javatest/weibo.xlsx",writeList);    
    70.         System.out.println("job has finished...........");  
    71.     }  
    72. }  

    清洗后数据:

  • 相关阅读:
    hdu 3339 最短路+01背包
    hdu 3584 三维树状数组
    hdu 最短路径的特殊运用
    螺旋矩阵(NOIP2014 普及组第三题)
    子矩阵(NOIP2014 普及组第四题)
    金币(NOIP2015 普及组第一题)
    扫雷游戏(NOIP2015 普及组第二题)
    求和(NOIP2015 普及组第三题)
    推销员(NOIP2015 普及组第四题)
    魔法阵(NOIP2016 普及组第四题)
  • 原文地址:https://www.cnblogs.com/gaochsh/p/7803256.html
Copyright © 2011-2022 走看看