还存在的问题是,对于其中分词借助的库还存在问题

参考此篇链接

  1. http://www.cnblogs.com/ywl925/archive/2013/08/26/3275878.html

具体代码部分:

具体代码在老电脑linux系统中

下面这个类:主要是,1列出某个目录下的所有文件名。2,读取某个特定文件

  1. package com.bobo.paper.util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11.  
  12. public class FileUtil {
  13.  
  14. public static ArrayList<String> FileList = new ArrayList<String>(); // the list of file
  15. /**
  16. * 列出某個目錄及其子目錄下所有的文件列表
  17. * @param filepath 目錄路徑
  18. * @return 該路徑及其子路經下的所有文件名列表
  19. * @throws FileNotFoundException
  20. * @throws IOException
  21. */
  22. public static List<String> readDirs(String filepath) throws FileNotFoundException, IOException
  23. {
  24. try
  25. {
  26. File file = new File(filepath);
  27. if(!file.isDirectory())
  28. {
  29. System.out.println("输入的不是目錄名称;");
  30. System.out.println("filepath:" + file.getAbsolutePath());
  31. }
  32. else
  33. {
  34. String[] flist = file.list();
  35. for(int i = ; i < flist.length; i++)
  36. {
  37. File newfile = new File(filepath + "/" + flist[i]);
  38. if(!newfile.isDirectory())
  39. {
  40. FileList.add(newfile.getAbsolutePath());
  41. }
  42. else if(newfile.isDirectory()) //if file is a directory, call ReadDirs
  43. {
  44. readDirs(filepath + "/" + flist[i]);
  45. }
  46. }
  47. }
  48. }catch(FileNotFoundException e)
  49. {
  50. System.out.println(e.getMessage());
  51. }
  52. return FileList;
  53. }
  54. /**
  55. * 讀取文件內容,以字符串的方式返回
  56. * @param file 需要讀取的文件名
  57. * @return 返回讀取的文件內容構成的字符串,行之間用\r\n進行分割
  58. * @throws FileNotFoundException
  59. * @throws IOException
  60. */
  61. public static String readFile(String file) throws FileNotFoundException, IOException
  62. {
  63. StringBuffer strSb = new StringBuffer(); //String is constant, StringBuffer can be changed.
  64. InputStreamReader inStrR = new InputStreamReader(new FileInputStream(file), "gbk"); //byte streams to character streams
  65. BufferedReader br = new BufferedReader(inStrR);
  66. String line = br.readLine();
  67. while(line != null){
  68. strSb.append(line).append("\r\n");
  69. line = br.readLine();
  70. }
  71.  
  72. return strSb.toString();
  73. }
  74.  
  75. }

FileUtil

下面这个类主要用于分词

  1. package com.bobo.paper.util;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5.  
  6. import org.wltea.analyzer.lucene.IKAnalyzer;
  7.  
  8. public class CutWordsUtil {
  9.  
  10. /**
  11. * 进行分词操作
  12. * @param file
  13. * @return
  14. * @throws IOException
  15. */
  16. public static ArrayList<String> cutWords(String file) throws IOException{
  17.  
  18. ArrayList<String> words = new ArrayList<String>();
  19. String text = FileUtil.readFile(file);
  20. IKAnalyzer analyzer = new IKAnalyzer();
  21. // 这里貌似缺少一个分词jar包进一步依赖的包?
  22.  
  23. // analyzer.split(text);
  24. //这个分词的工具,回头要以下即可
  25. return null;
  26.  
  27. }
  28.  
  29. }

CutWords

下面这个类主要实现tf-idf算法

  1. package com.bobo.paper.athology;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import com.bobo.paper.util.CutWordsUtil;
  11. import com.bobo.paper.util.FileUtil;
  12.  
  13. public class TfIdfAthology {
  14.  
  15. /**
  16. * 统计各个词语列表中各个词语出现的次数
  17. * @param cutwords 分词之后的词语列表
  18. * @return 返回一个hashmap,key为词,value为词出现的次数
  19. */
  20. public static HashMap<String, Integer> normalTF(ArrayList<String> cutwords){
  21. HashMap<String, Integer> resTF = new HashMap<String, Integer>();
  22.  
  23. for(String word : cutwords){
  24. if(resTF.get(word) == null){
  25. resTF.put(word, );
  26. System.out.println(word);
  27. }
  28. else{
  29. resTF.put(word, resTF.get(word) + );
  30. System.out.println(word.toString());
  31. }
  32. }
  33. return resTF;
  34. }
  35. /**
  36. * 统计词频,即tf值
  37. * @param cutwords 分词之后的词语列表
  38. * @return
  39. */
  40. public static HashMap<String, Float> tf(ArrayList<String> cutwords){
  41. HashMap<String, Float> resTF = new HashMap<String, Float>();
  42.  
  43. int wordLen = cutwords.size();
  44. HashMap<String, Integer> intTF = normalTF(cutwords);
  45.  
  46. Iterator iter = intTF.entrySet().iterator(); //iterator for that get from TF
  47. while(iter.hasNext()){
  48. Map.Entry entry = (Map.Entry)iter.next();
  49. resTF.put(entry.getKey().toString(), Float.parseFloat(entry.getValue().toString()) / wordLen);
  50. System.out.println(entry.getKey().toString() + " = "+ Float.parseFloat(entry.getValue().toString()) / wordLen);
  51. }
  52. return resTF;
  53. }
  54. /**
  55. * 将以个目录下所有的文件进行分词,返回一个HashMap<String, HashMap<String, Integer>> ,前面一个key是文件名,后面一个key是词,其值为该词出现的次数
  56. * @param dirc
  57. * @return
  58. * @throws IOException
  59. */
  60. public static HashMap<String, HashMap<String, Integer>> normalTFAllFiles(String dirc) throws IOException{
  61. HashMap<String, HashMap<String, Integer>> allNormalTF = new HashMap<String, HashMap<String,Integer>>();
  62. List<String> filelist = FileUtil.readDirs(dirc);
  63. for(String file : filelist){
  64. HashMap<String, Integer> dict = new HashMap<String, Integer>();
  65. ArrayList<String> cutwords = CutWordsUtil.cutWords(file); //get cut word for one file
  66.  
  67. dict = normalTF(cutwords);
  68. allNormalTF.put(file, dict);
  69. }
  70. return allNormalTF;
  71. }
  72. /**
  73. * 計算一個目錄下所有文件中詞語的詞頻
  74. * @param dirc 目錄名稱
  75. * @return 返回一個HashMap<String,HashMap<String, Float>>,第一個key是文件名,第二個key是詞,value是該詞語在該文件中的頻率
  76. * @throws IOException
  77. */
  78. public static HashMap<String,HashMap<String, Float>> tfAllFiles(String dirc) throws IOException{
  79. HashMap<String, HashMap<String, Float>> allTF = new HashMap<String, HashMap<String, Float>>();
  80. List<String> filelist = FileUtil.readDirs(dirc);
  81.  
  82. for(String file : filelist){
  83. HashMap<String, Float> dict = new HashMap<String, Float>();
  84. ArrayList<String> cutwords = CutWordsUtil.cutWords(file); //get cut words for one file
  85.  
  86. dict = tf(cutwords);
  87. allTF.put(file, dict);
  88. }
  89. return allTF;
  90. }
  91. /**
  92. * 計算词语的idf值 log(|D|/{包含该词语的文档个数+1})
  93. * @param all_tf 爲HashMap<String,HashMap<String, Float>>,第一個key爲文件名,第二個key爲詞語,float代表該詞語在本文件中的詞頻
  94. * @return
  95. */
  96. public static HashMap<String, Float> idf(HashMap<String,HashMap<String, Float>> all_tf){
  97. HashMap<String, Float> resIdf = new HashMap<String, Float>();
  98. //dict的key值为词,其value为出现该词的文档个数
  99. HashMap<String, Integer> dict = new HashMap<String, Integer>();
  100. int docNum = FileUtil.FileList.size();
  101. //循环所有的文件
  102. for(int i = ; i < docNum; i++){
  103. //all_tf中記錄的是
  104. HashMap<String, Float> temp = all_tf.get(FileUtil.FileList.get(i));
  105. Iterator iter = temp.entrySet().iterator();
  106.  
  107. while(iter.hasNext()){
  108. //循环一个文件中的所有词语的词频
  109. Map.Entry entry = (Map.Entry)iter.next();
  110. String word = entry.getKey().toString();
  111. //IDF的公式,idfi=log(|D|/|{j:ti屬於dj}|),其中|D|爲語料庫中的文件總數目,|{j:ti屬於dj}|指的是包含詞語ti的文件數目,如果该词语不在语料库中,就会导致被除数为零,因此一般情况下使用1 + |\{j : t_{i} \in d_{j}\}|
  112. if(dict.get(word) == null){
  113. dict.put(word, );
  114. }else {
  115. dict.put(word, dict.get(word) + );
  116. }
  117. }
  118. }
  119. System.out.println("IDF for every word is:");
  120. Iterator iter_dict = dict.entrySet().iterator();
  121. while(iter_dict.hasNext()){
  122. Map.Entry entry = (Map.Entry)iter_dict.next();
  123. float value = (float)Math.log(docNum / Float.parseFloat(entry.getValue().toString()));
  124. resIdf.put(entry.getKey().toString(), value);
  125. System.out.println(entry.getKey().toString() + " = " + value);
  126. }
  127. return resIdf;
  128. }
  129. /**
  130. * 计算某个词语的idf值
  131. * @param all_tf 记录所有词语tf值的map,第一个key为文件名,第二个key为词语
  132. * @param idfs 记录所有词语idf值的map,key为词语
  133. */
  134. public static void tf_idf(HashMap<String,HashMap<String, Float>> all_tf,HashMap<String, Float> idfs){
  135. HashMap<String, HashMap<String, Float>> resTfIdf = new HashMap<String, HashMap<String, Float>>();
  136. int docNum = FileUtil.FileList.size();
  137. for(int i = ; i < docNum; i++){
  138. String filepath = FileUtil.FileList.get(i);
  139. HashMap<String, Float> tfidf = new HashMap<String, Float>();
  140. HashMap<String, Float> temp = all_tf.get(filepath);
  141. Iterator iter = temp.entrySet().iterator();
  142. while(iter.hasNext()){
  143. Map.Entry entry = (Map.Entry)iter.next();
  144. String word = entry.getKey().toString();
  145. Float value = (float)Float.parseFloat(entry.getValue().toString()) * idfs.get(word);
  146. tfidf.put(word, value);
  147. }
  148. resTfIdf.put(filepath, tfidf);
  149. }
  150. System.out.println("TF-IDF for Every file is :");
  151. DisTfIdf(resTfIdf);
  152. }
  153. //這個主要用來顯示最終計算得到的tf-idf值
  154. public static void DisTfIdf(HashMap<String, HashMap<String, Float>> tfidf){
  155. Iterator iter1 = tfidf.entrySet().iterator();
  156. while(iter1.hasNext()){
  157. Map.Entry entrys = (Map.Entry)iter1.next();
  158. System.out.println("FileName: " + entrys.getKey().toString());
  159. System.out.print("{");
  160. HashMap<String, Float> temp = (HashMap<String, Float>) entrys.getValue();
  161. Iterator iter2 = temp.entrySet().iterator();
  162. while(iter2.hasNext()){
  163. Map.Entry entry = (Map.Entry)iter2.next();
  164. System.out.print(entry.getKey().toString() + " = " + entry.getValue().toString() + ", ");
  165. }
  166. System.out.println("}");
  167. }
  168.  
  169. }
  170. }

tfIdfAthology

最终的调用方法为:

  1. package com.bobo.paper;
  2.  
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5.  
  6. import com.bobo.paper.athology.TfIdfAthology;
  7.  
  8. public class Welcome {
  9.  
  10. /**
  11. * @param args
  12. */
  13. public static void main(String[] args) {
  14.  
  15. String file = "D:/testfiles";
  16.  
  17. HashMap<String, HashMap<String, Float>> all_tf;
  18. try {
  19. all_tf = TfIdfAthology.tfAllFiles(file);
  20. System.out.println();
  21. HashMap<String, Float> idfs = TfIdfAthology.idf(all_tf);
  22. System.out.println();
  23. TfIdfAthology.tf_idf(all_tf, idfs);
  24. } catch (IOException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }
  28.  
  29. }
  30.  
  31. }

Test

rf-idf的java实现的更多相关文章

  1. 利用JAVA计算TFIDF和Cosine相似度-学习版本

    写在前面的话,既然是学习版本,那么就不是一个好用的工程实现版本,整套代码全部使用List进行匹配效率可想而知. [原文转自]:http://computergodzilla.blogspot.com/ ...

  2. How to uninstall (remove) JAVA from OS X Lion

    Open terminal (Applications -> Utilities -> Terminal) To remove JVM enter folowing: sudo rm -r ...

  3. linux配置java环境变量jdk jre(详细)【转】

    linux配置java环境变量(详细) 本文完全引用自: http://www.cnblogs.com/samcn/archive/2011/03/16/1986248.html 一. 解压安装jdk ...

  4. linux JAVA_HOME和 java -version不匹配

    ~/.bashrc 中更新了jdk, JAVA_HOME 起效果了,但是java -version还是老的. 原因是/usr/bin/java   和usr/bin/javac是一个链接,得改. 使用 ...

  5. Linux更换jdk版本,java -version还是原来的版本问题

    服务器上默认安装版本是: 使用jenkins最新的安装包 2.73.1,启动报错52.0!需要使用1.8进行启动. 两种方式,要么tomcat直接指定,要么修改环境变量,这里我使用修改安装java版本 ...

  6. 吴裕雄--天生自然 HADOOP大数据分布式处理:安装配置JAVA

    tar -xzvf jdk-8u151-linux-x64.tar.gz -C /usr/local/src sudo vim /etc/profile .编辑/etc/profile # JAVA ...

  7. Linux学习笔记(整理记录)

    1.安装 (1):安装网址:http://www.jb51.net/os/78318.html 2.鸟哥的Linux命令学习 (1):显示系统目前所支持的语言:echo $LANG (2):修改语言成 ...

  8. Mac commands

    /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java uname -a 显示系统隐藏文件.在终端(Ter ...

  9. 容易忘记的几个Linux命令

    #查看文件或者目录的属性ls -ld filenamels -ld directory #vi编辑器输入:.,$d #清除全部内容 #修改管理员.用户密码passwd user #("use ...

  10. 练习 map集合被使用是因为具备映射关系 "进度班" "01" "张三" "进度班" "02" "李四" "J1701" "01" "王五" "J1701" "02" "王二" 此信息中,我们要怎样把上述信息装入集合中, 根据班级信息的到所有的所有信

    package com.rf.xs; import java.util.Arrays; public class Student01 { String name; int age; public St ...

随机推荐

  1. 软技能-代码外的生存指南PDF下载

    编程只是我们职业生涯中的一部分,我们还需要更多的其他技能 链接:https://pan.baidu.com/s/1d7z_7NCEFT2lsSWO1n-OuA 提取码:zj32 链接失效请留言

  2. 解决Jackson2反序列化LocalDateTime报错

    今天在整合redis和spring boot的时候,遇到了一个错误,记录一下. 报错如下: Could not read JSON: Cannot construct instance of `jav ...

  3. [19/09/19-星期四] Python中的字典和集合

    一.字典 # 字典 # 使用 {} 来创建字典 d = {} # 创建了一个空字典 # 创建一个保护有数据的字典 # 语法: # {key:value,key:value,key:value} # 字 ...

  4. JSP页面读取数据中的数据内容,出现乱码现象的解决方法

    1.首先要确保JSP页面的编码已修改为“utf-8”的字符编码: 2.然后再在jsp页面上添加代码进行设置: 先用getBytes()方法读出数据,然后再new String()方法设置格式为“utf ...

  5. MySQL-快速入门(1)基本数据库、表操作语句

    1.创建数据库 create database db_name;show create database db_name\G; //查看数据创建语句show databases; //查看当前创建的数 ...

  6. 防抖和节流 lodash插件

    lodash.debounce lodash.debounce(function(){ },1000) 函数防抖原理 调用函数时,马上清理定时器.然后再设置一个定时器包含函数

  7. uboot常用命令

    一. 常用简单命令 1.1. help命令 a. 帮助查看其他命令的使用方法,类型linux下man b. 示例: help help x210 # help help help [command . ...

  8. CSP-S全国模拟赛第二场 【nan】

    A.count 本场比赛最难的题... 隔板法组合数容斥 xjb 搞搞就好了 //by Judge #include<cstdio> #include<iostream> #d ...

  9. C#设计模式:备忘录模式(Memento Pattern)

    一,C#设计模式:备忘录模式(Memento Pattern) 1.发起人角色(Originator):记录当前时刻的内部状态,负责创建和恢复备忘录数据.负责创建一个备忘录Memento,用以记录当前 ...

  10. oracle的隐藏的东东

    1: 在oracle中存在一种特殊的表单:dual 这是一张伪表,不是真正存在的 在日期的查询和触发器等多处用到 只展示系统当前时间: select sysdate from dual; 触发器:往往 ...