Repository: hankcs/TextRank Branch: master Commit: eda5abe1bae5 Files: 9 Total size: 26.3 KB Directory structure: gitextract_ni6c1bxe/ ├── .classpath ├── .gitignore ├── .project ├── LICENSE ├── README.md ├── pom.xml └── src/ └── main/ └── java/ └── com/ └── hankcs/ └── textrank/ ├── BM25.java ├── TextRankKeyword.java └── TextRankSummary.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .classpath ================================================ ================================================ FILE: .gitignore ================================================ /.idea /out *.class # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* /*.eml /*.iml ================================================ FILE: .project ================================================ TextRank org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ TextRank ======== TextRank算法提取关键词与自动摘要的Java实现 ## 注意 **TextRank已经集成到[HanLP](https://github.com/hankcs/HanLP)中,本项目不再维护。** TextRankKeyword提取关键词 -- - 调用方法 ```java public static void main(String[] args) { String content = "程序员(英文Programmer)是从事程序开发、维护的专业人员。一般将程序员分为程序设计人员和程序编码人员,但两者的界限并不非常清楚,特别是在中国。软件从业人员分为初级程序员、高级程序员、系统分析员和项目经理四大类。"; System.out.println(new TextRankKeyword().getKeyword("", content)); } ``` - 算法详解 TextRank是在Google的PageRank算法启发下,针对文本里的句子设计的权重算法,目标是自动摘要。 详见[《TextRank算法提取关键词的Java实现》][1] - 关于分词 分词不是TextRank关注的重点,项目中的警告是分词库发出,不影响功能。 TextRankSummary自动摘要 -- - 调用方法 ```java public static void main(String[] args) { String document = "算法可大致分为基本算法、数据结构的算法、数论算法、计算几何的算法、图的算法、动态规划以及数值分析、加密算法、排序算法、检索算法、随机化算法、并行算法、厄米变形模型、随机森林算法。\n" + "算法可以宽泛的分为三类,\n" + "一,有限的确定性算法,这类算法在有限的一段时间内终止。他们可能要花很长时间来执行指定的任务,但仍将在一定的时间内终止。这类算法得出的结果常取决于输入值。\n" + "二,有限的非确定算法,这类算法在有限的时间内终止。然而,对于一个(或一些)给定的数值,算法的结果并不是唯一的或确定的。\n" + "三,无限的算法,是那些由于没有定义终止定义条件,或定义的条件无法由输入的数据满足而不终止运行的算法。通常,无限算法的产生是由于未能确定的定义终止条件。"; System.out.println(TextRankSummary.getTopSentenceList(document, 3)); } ``` - 算法详解 通过句子的相关程度(BM25相关度)决定票的权重,迭代投票得出最终权重。 详见[《TextRank算法自动摘要的Java实现》][2] TODO -- - 自然语言处理任重道远,本项目只是对TextRank的一份简明实现,效果和性能请自行评估。 - 我写了[一系列入门笔记][3],欢迎NLP领域的朋友[前来交流、指导我的学习][3]。 - 事实上,我正在开发一个完备的汉语处理包,目前能够提供分词、词性标注、命名实体识别、关键字提取、短语提取、自动摘要、自动推荐等功能,未来可能开源并逐步实现依存关系、句法树等功能,敬请期待。 [1]: http://www.hankcs.com/nlp/textrank%E7%AE%97%E6%B3%95%E6%8F%90%E5%8F%96%E5%85%B3%E9%94%AE%E8%AF%8D%E7%9A%84java%E5%AE%9E%E7%8E%B0.html [2]: http://www.hankcs.com/nlp/textrank-algorithm-java-implementation-of-automatic-abstract.html [3]: http://www.hankcs.com/category/nlp/ ================================================ FILE: pom.xml ================================================ 4.0.0 DemoHanLPPortable hanlp-portable-demo 1.0-SNAPSHOT com.hankcs hanlp portable-1.1.5 ================================================ FILE: src/main/java/com/hankcs/textrank/BM25.java ================================================ package com.hankcs.textrank; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * 搜索相关性评分算法 * @author hankcs */ public class BM25 { /** * 文档句子的个数 */ int D; /** * 文档句子的平均长度 */ double avgdl; /** * 拆分为[句子[单词]]形式的文档 */ List> docs; /** * 文档中每个句子中的每个词与词频 */ Map[] f; /** * 文档中全部词语与出现在几个句子中 */ Map df; /** * IDF */ Map idf; /** * 调节因子 */ final static float k1 = 1.5f; /** * 调节因子 */ final static float b = 0.75f; public BM25(List> docs) { this.docs = docs; D = docs.size(); for (List sentence : docs) { avgdl += sentence.size(); } avgdl /= D; f = new Map[D]; df = new TreeMap(); idf = new TreeMap(); init(); } /** * 在构造时初始化自己的所有参数 */ private void init() { int index = 0; for (List sentence : docs) { Map tf = new TreeMap(); for (String word : sentence) { Integer freq = tf.get(word); freq = (freq == null ? 0 : freq) + 1; tf.put(word, freq); } f[index] = tf; for (Map.Entry entry : tf.entrySet()) { String word = entry.getKey(); Integer freq = df.get(word); freq = (freq == null ? 0 : freq) + 1; df.put(word, freq); } ++index; } for (Map.Entry entry : df.entrySet()) { String word = entry.getKey(); Integer freq = entry.getValue(); idf.put(word, Math.log(D - freq + 0.5) - Math.log(freq + 0.5)); } } public double sim(List sentence, int index) { double score = 0; for (String word : sentence) { if (!f[index].containsKey(word)) continue; int d = docs.get(index).size(); Integer wf = f[index].get(word); score += (idf.get(word) * wf * (k1 + 1) / (wf + k1 * (1 - b + b * d / avgdl))); } return score; } public double[] simAll(List sentence) { double[] scores = new double[D]; for (int i = 0; i < D; ++i) { scores[i] = sim(sentence, i); } return scores; } } ================================================ FILE: src/main/java/com/hankcs/textrank/TextRankKeyword.java ================================================ package com.hankcs.textrank; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import com.hankcs.hanlp.seg.common.Term; import java.util.*; /** * TextRank关键词提取 * @author hankcs */ public class TextRankKeyword { public static final int nKeyword = 10; /** * 阻尼系数(DampingFactor),一般取值为0.85 */ static final float d = 0.85f; /** * 最大迭代次数 */ static final int max_iter = 200; static final float min_diff = 0.001f; public TextRankKeyword() { // jdk bug : Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract! System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); } public String getKeyword(String title, String content) { List termList = HanLP.segment(title + content); // System.out.println(termList); List wordList = new ArrayList(); for (Term t : termList) { if (shouldInclude(t)) { wordList.add(t.word); } } // System.out.println(wordList); Map> words = new HashMap>(); Queue que = new LinkedList(); for (String w : wordList) { if (!words.containsKey(w)) { words.put(w, new HashSet()); } que.offer(w); if (que.size() > 5) { que.poll(); } for (String w1 : que) { for (String w2 : que) { if (w1.equals(w2)) { continue; } words.get(w1).add(w2); words.get(w2).add(w1); } } } // System.out.println(words); Map score = new HashMap(); for (int i = 0; i < max_iter; ++i) { Map m = new HashMap(); float max_diff = 0; for (Map.Entry> entry : words.entrySet()) { String key = entry.getKey(); Set value = entry.getValue(); m.put(key, 1 - d); for (String other : value) { int size = words.get(other).size(); if (key.equals(other) || size == 0) continue; m.put(key, m.get(key) + d / size * (score.get(other) == null ? 0 : score.get(other))); } 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) break; } List> entryList = new ArrayList>(score.entrySet()); Collections.sort(entryList, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return (o1.getValue() - o2.getValue() > 0 ? -1 : 1); } }); // System.out.println(entryList); String result = ""; for (int i = 0; i < nKeyword; ++i) { result += entryList.get(i).getKey() + '#'; } return result; } public static void main(String[] args) { String content = "程序员(英文Programmer)是从事程序开发、维护的专业人员。一般将程序员分为程序设计人员和程序编码人员,但两者的界限并不非常清楚,特别是在中国。软件从业人员分为初级程序员、高级程序员、系统分析员和项目经理四大类。"; System.out.println(new TextRankKeyword().getKeyword("", content)); } /** * 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词 * @param term * @return 是否应当 */ public boolean shouldInclude(Term term) { return CoreStopWordDictionary.shouldInclude(term); } } ================================================ FILE: src/main/java/com/hankcs/textrank/TextRankSummary.java ================================================ package com.hankcs.textrank; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import com.hankcs.hanlp.seg.common.Term; import java.util.*; /** * TextRank 自动摘要 * @author hankcs */ public class TextRankSummary { /** * 阻尼系数(DampingFactor),一般取值为0.85 */ final double d = 0.85f; /** * 最大迭代次数 */ final int max_iter = 200; final double min_diff = 0.001f; /** * 文档句子的个数 */ int D; /** * 拆分为[句子[单词]]形式的文档 */ List> docs; /** * 排序后的最终结果 score <-> index */ TreeMap top; /** * 句子和其他句子的相关程度 */ double[][] weight; /** * 该句子和其他句子相关程度之和 */ double[] weight_sum; /** * 迭代之后收敛的权重 */ double[] vertex; /** * BM25相似度 */ BM25 bm25; public TextRankSummary(List> docs) { this.docs = docs; bm25 = new BM25(docs); D = docs.size(); weight = new double[D][D]; weight_sum = new double[D]; vertex = new double[D]; top = new TreeMap(Collections.reverseOrder()); solve(); } private void solve() { int cnt = 0; for (List sentence : docs) { double[] scores = bm25.simAll(sentence); // System.out.println(Arrays.toString(scores)); weight[cnt] = scores; weight_sum[cnt] = sum(scores) - scores[cnt]; // 减掉自己,自己跟自己肯定最相似 vertex[cnt] = 1.0; ++cnt; } for (int _ = 0; _ < max_iter; ++_) { double[] m = new double[D]; double max_diff = 0; for (int i = 0; i < D; ++i) { m[i] = 1 - d; for (int j = 0; j < D; ++j) { if (j == i || weight_sum[j] == 0) continue; m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]); } double diff = Math.abs(m[i] - vertex[i]); if (diff > max_diff) { max_diff = diff; } } vertex = m; if (max_diff <= min_diff) break; } // 我们来排个序吧 for (int i = 0; i < D; ++i) { top.put(vertex[i], i); } } /** * 获取前几个关键句子 * @param size 要几个 * @return 关键句子的下标 */ public int[] getTopSentence(int size) { Collection values = top.values(); size = Math.min(size, values.size()); int[] indexArray = new int[size]; Iterator it = values.iterator(); for (int i = 0; i < size; ++i) { indexArray[i] = it.next(); } return indexArray; } /** * 简单的求和 * @param array * @return */ private static double sum(double[] array) { double total = 0; for (double v : array) { total += v; } return total; } public static void main(String[] args) { String document = "算法可大致分为基本算法、数据结构的算法、数论算法、计算几何的算法、图的算法、动态规划以及数值分析、加密算法、排序算法、检索算法、随机化算法、并行算法、厄米变形模型、随机森林算法。\n" + "算法可以宽泛的分为三类,\n" + "一,有限的确定性算法,这类算法在有限的一段时间内终止。他们可能要花很长时间来执行指定的任务,但仍将在一定的时间内终止。这类算法得出的结果常取决于输入值。\n" + "二,有限的非确定算法,这类算法在有限的时间内终止。然而,对于一个(或一些)给定的数值,算法的结果并不是唯一的或确定的。\n" + "三,无限的算法,是那些由于没有定义终止定义条件,或定义的条件无法由输入的数据满足而不终止运行的算法。通常,无限算法的产生是由于未能确定的定义终止条件。"; System.out.println(TextRankSummary.getTopSentenceList(document, 3)); } /** * 将文章分割为句子 * @param document * @return */ static List spiltSentence(String document) { List sentences = new ArrayList(); if (document == null) return sentences; for (String line : document.split("[\r\n]")) { line = line.trim(); if (line.length() == 0) continue; for (String sent : line.split("[,,。::“”??!!;;]")) { sent = sent.trim(); if (sent.length() == 0) continue; sentences.add(sent); } } return sentences; } /** * 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词 * @param term * @return 是否应当 */ public static boolean shouldInclude(Term term) { return CoreStopWordDictionary.shouldInclude(term); } /** * 一句话调用接口 * @param document 目标文档 * @param size 需要的关键句的个数 * @return 关键句列表 */ public static List getTopSentenceList(String document, int size) { List sentenceList = spiltSentence(document); List> docs = new ArrayList>(); for (String sentence : sentenceList) { List termList = HanLP.segment(sentence); List wordList = new LinkedList(); for (Term term : termList) { if (shouldInclude(term)) { wordList.add(term.word); } } docs.add(wordList); } TextRankSummary textRankSummary = new TextRankSummary(docs); int[] topSentence = textRankSummary.getTopSentence(size); List resultList = new LinkedList(); for (int i : topSentence) { resultList.add(sentenceList.get(i)); } return resultList; } }