基于TextRank算法提取關(guān)鍵詞——Java實(shí)現(xiàn)

依賴

 <dependency>
     <groupId>com.janeluo</groupId>
     <artifactId>ikanalyzer</artifactId>
     <version>2012_u6</version>
 </dependency>

代碼

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

/**
 * @author yuyufeng
 * @date 2017/11/3
 */
public class Demo {
    public static void main(String[] args) {

        List<String> keyWords = new ArrayList<>();
        int k = 2;  //窗口大小/2
        float d = 0.85f;
        /**
         * 標(biāo)點(diǎn)符號(hào)、常用詞、以及“名詞、動(dòng)詞、形容詞、副詞之外的詞”
         */
        Set<String> stopWordSet = new HashSet<String>();
        stopWordSet.add("是");
        stopWordSet.add("的");
        stopWordSet.add("地");
        stopWordSet.add("從");
        stopWordSet.add("將");
        stopWordSet.add("但");
        stopWordSet.add("都");
        stopWordSet.add("和");
        stopWordSet.add("為");
        stopWordSet.add("讓");
        stopWordSet.add("在");
        stopWordSet.add("由");
        stopWordSet.add("上");
        String field = "PageRank近似于一個(gè)用戶,是指在Internet上隨機(jī)地單擊鏈接將會(huì)到達(dá)特定網(wǎng)頁(yè)的可能性。通常,能夠從更多地方到達(dá)的網(wǎng)頁(yè)更為重要,因此具有更高的PageRank。每個(gè)到其他網(wǎng)頁(yè)的鏈接,都增加了該網(wǎng)頁(yè)的PageRank。具有較高PageRank的網(wǎng)頁(yè)一般都是通過(guò)更多其他網(wǎng)頁(yè)的鏈接而提高的。";


        Analyzer analyzer = new IKAnalyzer(true);
        TokenStream ts = null;
        //分詞
        try {
            ts = analyzer.tokenStream("myfield", new StringReader(field));
            OffsetAttribute offset = (OffsetAttribute) ts.addAttribute(OffsetAttribute.class);
            CharTermAttribute term = (CharTermAttribute) ts.addAttribute(CharTermAttribute.class);
            TypeAttribute type = (TypeAttribute) ts.addAttribute(TypeAttribute.class);
            ts.reset();

            while (ts.incrementToken()) {
                if (!stopWordSet.contains(term.toString())) {
                    keyWords.add(term.toString());
                }
            }
            ts.end();
        } catch (IOException var14) {
            var14.printStackTrace();
        } finally {
            if (ts != null) {
                try {
                    ts.close();
                } catch (IOException var13) {
                    var13.printStackTrace();
                }
            }

        }

        Map<String, Set<String>> relationWords = new HashMap<>();


        //獲取每個(gè)關(guān)鍵詞 前后k個(gè)的組合
        for (int i = 0; i < keyWords.size(); i++) {
            String keyword = keyWords.get(i);
            Set<String> keySets = relationWords.get(keyword);
            if (keySets == null) {
                keySets = new HashSet<>();
                relationWords.put(keyword, keySets);
            }

            for (int j = i - k; j <= i + k; j++) {
                if (j < 0 || j >= keyWords.size() || j == i) {
                    continue;
                } else {
                    keySets.add(keyWords.get(j));
                }
            }
        }

       /* for (String s : relationWords.keySet()) {
            System.out.print(s+" ");
            for (String s1 : relationWords.get(s)) {
                System.out.print(s1+" ");
            }
            System.out.println();
        }*/


        Map<String, Float> score = new HashMap<>();
        float min_diff = 0.1f; //差值最小
        int max_iter = 100;//最大迭代次數(shù)

        //迭代
        for (int i = 0; i < max_iter; i++) {
            Map<String, Float> m = new HashMap<>();
            float max_diff = 0;
            for (String key : relationWords.keySet()) {
                Set<String> value = relationWords.get(key);
                //先給每個(gè)關(guān)鍵詞一個(gè)默認(rèn)rank值
                m.put(key, 1 - d);
                //一個(gè)關(guān)鍵詞的TextRank由其它成員投票出來(lái)
                for (String other : value) {
                    int size = relationWords.get(other).size();
                    if (key.equals(other) || size == 0) {
                        continue;
                    } else {
                        m.put(key, m.get(key) + d / size * (score.get(other) == null ? 0 : score.get(other)));
                    }
                }
//                System.out.println("m.get(key):"+m.get(key)+" score:"+(score.get(key) == null ? 0 : score.get(key)));
                max_diff = Math.max(max_diff, Math.abs(m.get(key) - (score.get(key) == null ? 0 : score.get(key))));
            }

            score = m;
            if (max_diff <= min_diff) {
                System.out.println("迭代次數(shù):" + i);
                break;
            }
        }

        List<Score> scores = new ArrayList<>();
        for (String s : score.keySet()) {
            Score score1 = new Score();
            score1.key = s;
            score1.significance = score.get(s);
            scores.add(score1);
        }

        scores.sort(new Comparator<Score>() {
            @Override
            public int compare(Score o1, Score o2) {
                if (o2.significance - o1.significance > 0) {
                    return 1;
                } else {
                    return -1;
                }

            }
        });

        for (Score score1 : scores) {
            System.out.println(score1);
        }

    }
}

class Score {
    String key;
    float significance;

    @Override
    public String toString() {
        return "關(guān)鍵詞=" + key +
                ", 重要程度=" + significance;
    }
}

運(yùn)行結(jié)果
迭代次數(shù):11

關(guān)鍵詞=網(wǎng)頁(yè), 重要程度=2.8311346
關(guān)鍵詞=鏈接, 重要程度=1.646728
關(guān)鍵詞=pagerank, 重要程度=1.6038197
關(guān)鍵詞=更多, 重要程度=1.2489531
關(guān)鍵詞=到達(dá), 重要程度=1.1083827
關(guān)鍵詞=具有, 重要程度=0.98187566
關(guān)鍵詞=其他, 重要程度=0.9651773
關(guān)鍵詞=用戶, 重要程度=0.81595975
關(guān)鍵詞=指在, 重要程度=0.8086006
關(guān)鍵詞=internet, 重要程度=0.80388165
關(guān)鍵詞=一個(gè), 重要程度=0.787644
關(guān)鍵詞=隨機(jī), 重要程度=0.7764552
關(guān)鍵詞=單擊, 重要程度=0.76052386
關(guān)鍵詞=將會(huì), 重要程度=0.71690917
關(guān)鍵詞=能夠, 重要程度=0.7066941
關(guān)鍵詞=可能性, 重要程度=0.70503104
關(guān)鍵詞=更高, 重要程度=0.7045265
關(guān)鍵詞=每個(gè), 重要程度=0.7005399
關(guān)鍵詞=特定, 重要程度=0.6963727
關(guān)鍵詞=通過(guò), 重要程度=0.69495517
關(guān)鍵詞=因此, 重要程度=0.69311315
關(guān)鍵詞=通常, 重要程度=0.69245243
關(guān)鍵詞=該, 重要程度=0.6918771
關(guān)鍵詞=一般, 重要程度=0.6895788
關(guān)鍵詞=都是, 重要程度=0.686642
關(guān)鍵詞=到, 重要程度=0.68152785
關(guān)鍵詞=更為重要, 重要程度=0.68064004
關(guān)鍵詞=地方, 重要程度=0.6771895
關(guān)鍵詞=近似于, 重要程度=0.6137907
關(guān)鍵詞=而, 重要程度=0.594995
關(guān)鍵詞=增加了, 重要程度=0.5508093
關(guān)鍵詞=較高, 重要程度=0.5392841
關(guān)鍵詞=提高, 重要程度=0.44995427

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 獨(dú)角獸的青春閱讀 243評(píng)論 0 0
  • 春秋戰(zhàn)國(guó)時(shí)期,周王朝的勢(shì)力日漸衰弱。各路諸侯群雄紛爭(zhēng),春秋五霸,戰(zhàn)國(guó)七雄,連年混戰(zhàn)不休。 何為戰(zhàn)國(guó)?是因?yàn)閼?zhàn)爭(zhēng)太多...
    謝紫洋閱讀 560評(píng)論 0 1
  • 有可能失敗是一種財(cái)富,雖然心酸,但也從中收獲了很多,有友情,有愛(ài)情,有迷茫,有膽怯,又害怕,又有坦然。從這次經(jīng)歷中...
    Vicky_x_y閱讀 135評(píng)論 0 0
  • 晨光路過(guò)我的房 鳥(niǎo)鳴敲響我的窗 夢(mèng)中的你,是否已起床 昨夜,又在夢(mèng)中與你相遇 久違的你,還是不言不語(yǔ) 醒來(lái)的我,依...
    Dreaming丫頭閱讀 513評(píng)論 2 1

友情鏈接更多精彩內(nèi)容