網頁本文抽取(包含提取圖片)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   使用   java   ar   

轉自:http://bbs.it-home.org/thread-12676-1-1.html

 

 

/** *@author Xin Chen *Created on 2009-11-11 *Updated on 2010-08-09 *Email:  [email protected] *Blog:   http://hi.baidu.com/愛心同盟_陳鑫 *Modified By : Yang @ http://www.chainlt.com */import java.util.ArrayList;import java.util.Arrays;import java.util.List;import dbhelper.TextTool;/** * <p> * 線上性時間內抽取主題類(新聞、部落格等)網頁的本文。 採用了<b>基於行塊分布函數</b>的方法,為保持通用性沒有針對特定網站編寫規則。 * </p> *  * @author Chen Xin * @version 1.0, 2009-11-11 */public class TextExtract {    private static List<String> lines;    private final static int blocksWidth;    private static int threshold;    private static String html;    private static boolean flag;    private static int start;    private static int end;    private static StringBuilder text;    private static ArrayList<Integer> indexDistribution;    private static List<String> old_lines;    private static String oldhtml;    static {        lines = new ArrayList<String>();        indexDistribution = new ArrayList<Integer>();        text = new StringBuilder();        blocksWidth = 3;        flag = false;        /* 當待抽取的網頁本文中遇到成塊的新聞標題未剔除時,只要增大此閾值即可。 */        /* 閾值增大,準確率提升,召回率下降;值變小,雜訊會大,但可以保證抽到只有一句話的本文 */        threshold = 86;    }    public static void setthreshold(int value) {        threshold = value;    }    /**     * 抽取網頁本文,不判斷該網頁是否是目錄型。即已知傳入的肯定是可以抽取本文的主題類網頁。     *      * @param _html     *            網頁HTML字串     *      * @return 網頁本文string     */    public static String parse(String _html) {        return parse(_html, false);    }    /**     * 判斷傳入HTML,若是主題類網頁,則抽取本文;否則輸出<b>"unkown"</b>。     *      * @param _html     *            網頁HTML字串     * @param _flag     *            true進行主題類判斷, 省略此參數則預設為false     * @return 網頁本文string     */    public static String parse(String _html, boolean _flag) {        flag = _flag;        html = _html;        preProcess();        // System.out.println(html);        return getText();    }    private static void preProcess() {        html = html.replaceAll("(?is)<!DOCTYPE.*?>", "");        html = html.replaceAll("(?is)<!--.*?-->", "");// remove html comment        html = html.replaceAll("(?is)<script.*?>.*?</script>", "");// remove                                                                    // javascript        html = html.replaceAll("(?is)<style.*?>.*?</style>", "");// remove css        html = html.replaceAll("(?is)style=\".*?\"", "");// remove css        html = html.replaceAll("&.{2,5};|&#.{2,5};", " ");// remove special char        oldhtml = html;        html = html.replaceAll("(?is)<.*?>", "");        // <!--[if !IE]>|xGv00|9900d21eb16fa4350a3001b3974a9415<![endif]-->    }    private static String getText() {        lines = Arrays.asList(html.split("\n"));        old_lines = Arrays.asList(oldhtml.split("\n"));        indexDistribution.clear();        boolean haveimg_arr[] = new boolean[old_lines.size()];        for (int i = 0; i < lines.size() - blocksWidth; i++) {            int wordsNum = 0;            for (int j = i; j < i + blocksWidth; j++) {                lines.set(j, lines.get(j).replaceAll("\\s+", ""));                wordsNum += lines.get(j).length();            }            indexDistribution.add(wordsNum);            // System.out.println(wordsNum);            if (old_lines.get(i).toLowerCase().contains("<img")) {                haveimg_arr[i] = true;            }        }        start = -1;        end = -1;        boolean boolstart = false, boolend = false;        text.setLength(0);        for (int i = 0; i < indexDistribution.size() - 1; i++) {            if (indexDistribution.get(i) > threshold && !boolstart) {                if (indexDistribution.get(i + 1).intValue() != 0                        || indexDistribution.get(i + 2).intValue() != 0                        || indexDistribution.get(i + 3).intValue() != 0) {                    boolstart = true;                    start = i;                    continue;                }            }            if (boolstart) {                if (haveimg_arr[i]) {                    continue;                }                if (indexDistribution.get(i).intValue() == 0                        || indexDistribution.get(i + 1).intValue() == 0) {                    end = i;                    boolend = true;                }            }            if (boolend) {                StringBuilder tmp = new StringBuilder();                // System.out.println(start+1 + "\t\t" + end+1);                for (int ii = start; ii <= end; ii++) {                    if (haveimg_arr[ii]) {                        String img = getImg(old_lines.get(ii));                        if (img == null)                            continue;                        tmp.append(img + "\n");                        continue;                    }                    if (lines.get(ii).length() < 5)                        continue;                    tmp.append("<p>" + lines.get(ii) + "</p>\n");                }                String str = tmp.toString();                // System.out.println(str);                if (str.contains("Copyright") || str.contains("著作權"))                    continue;                text.append(str);                boolstart = boolend = false;            }        }        return text.toString();    }    public static String getImg(String s) {        String img = TextTool.getBetweenOne(s, "<img", "</img>");        if (img == null) {            img = TextTool.getBetweenOne(s, "<img", "/>");        } else {            img = "<img" + img + "</img>";        }        if (img != null) {            img = "<img" + img + "/>";        }        return img;    }}

 

 

 

PS:

Q:經常看見的正則前面的 (?i) (?s) (?m) (?is) (?im) 是什麼意思?
A: 稱為內聯匹配模式,通常用內聯匹配模式代替使用枚舉值RegexOptions指定的全域匹配模式,寫起來更簡潔。
  (?i) 表示所在位置右側的運算式開啟忽略大小寫入模式
  (?s) 表示所在位置右側的運算式開啟單行模式。
  更改句點字元 (.) 的含義,以使它與每個字元(而不是除 \n 之外的所有字元)匹配。
  注意:(?s)通常在匹配有換行的文本時使用
  (?m) 表示所在位置右側的表示式開啟指定多行模式。
  更改 ^ 和 $ 的含義,以使它們分別與任何行的開頭和結尾匹配,
  而不只是與整個字串的開頭和結尾匹配。
  注意:(?m)只有在Regex中涉及到多行的“^”和“$”的匹配時,才使用Multiline模式。
  上面的匹配模式可以組合使用,比如(?is),(?im)。
  另外,還可以用(?i:exp)或者(?i)exp(?-i)來指定匹配的有效範圍。

網頁本文抽取(包含提取圖片)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.