---
title: "TF-IDF（转）输出到文本"
author: "forever1220"
date: "2014-08-02T22:04:45Z"
tags: []
categories: ["非技术"]
slug: "tf-idf"
draft: false
lastmod: "2014-08-02T22:04:45Z"
id: 2099698
url: "https://forever1220.iteye.com/blog/2099698"
---

import java.io.\*; import java.util.\*; import org.wltea.analyzer.lucene.IKAnalyzer; public class ReadFiles { /\** * @param args \*/ private static ArrayList FileList = new ArrayList(); // the list of file //get list of file for the directory, including sub-directory of it public static List readDirs(String filepath) throws FileNotFoundException, IOException { try { File file = new File(filepath); if(!file.isDirectory()) { System.out.println("输入的\[]"); System.out.println("filepath:" + file.getAbsolutePath()); } else { String\[] flist = file.list(); for(int i = 0; i &lt; flist.length; i++) { File newfile = new File(filepath + "\\\\" + flist\[i]); if(!newfile.isDirectory()) { FileList.add(newfile.getAbsolutePath()); } else if(newfile.isDirectory()) //if file is a directory, call ReadDirs { readDirs(filepath + "\\\\" + flist\[i]); } } } }catch(FileNotFoundException e) { System.out.println(e.getMessage()); } return FileList; } //read file public static String readFile(String file) throws FileNotFoundException, IOException { StringBuffer strSb = new StringBuffer(); //String is constant， StringBuffer can be changed. InputStreamReader inStrR = new InputStreamReader(new FileInputStream(file), "gbk"); //byte streams to character streams BufferedReader br = new BufferedReader(inStrR); String line = br.readLine(); while(line != null){ strSb.append(line).append("\\r\\n"); line = br.readLine(); } return strSb.toString(); } //word segmentation public static ArrayList cutWords(String file) throws IOException{ ArrayList words = new ArrayList(); String text = ReadFiles.readFile(file); IKAnalyzer analyzer = new IKAnalyzer(); words = analyzer.split(text); return words; } //term frequency in a file, times for each word public static HashMap normalTF(ArrayList cutwords){ HashMap resTF = new HashMap(); for(String word : cutwords){ if(resTF.get(word) == null){ resTF.put(word, 1); System.out.println(word); } else{ resTF.put(word, resTF.get(word) + 1); System.out.println(word.toString()); } } return resTF; } //term frequency in a file, frequency of each word public static HashMap tf(ArrayList cutwords){ HashMap resTF = new HashMap(); int wordLen = cutwords.size(); HashMap intTF = ReadFiles.normalTF(cutwords); Iterator iter = intTF.entrySet().iterator(); //iterator for that get from TF try { FileWriter writer = new FileWriter("d:\\\\DF.txt", true); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); resTF.put(entry.getKey().toString(), Float.parseFloat(entry.getValue().toString()) / wordLen); System.out.println(entry.getKey().toString() + " = "+ Float.parseFloat(entry.getValue().toString()) / wordLen); // 输出到文件 writer.write(entry.getKey().toString() + " = "+ Float.parseFloat(entry.getValue().toString()) / wordLen+"\\r\\n"); }//end with while writer.close(); } catch(Exception ex) { } return resTF; } //tf times for file public static HashMap&gt; normalTFAllFiles(String dirc) throws IOException{ HashMap&gt; allNormalTF = new HashMap&gt;(); List filelist = ReadFiles.readDirs(dirc); for(String file : filelist){ HashMap dict = new HashMap(); ArrayList cutwords = ReadFiles.cutWords(file); //get cut word for one file dict = ReadFiles.normalTF(cutwords); allNormalTF.put(file, dict); } return allNormalTF; } //tf for all file public static HashMap&gt; tfAllFiles(String dirc) throws IOException{ HashMap&gt; allTF = new HashMap&gt;(); List filelist = ReadFiles.readDirs(dirc); for(String file : filelist){ HashMap dict = new HashMap(); ArrayList cutwords = ReadFiles.cutWords(file); //get cut words for one file dict = ReadFiles.tf(cutwords); allTF.put(file, dict); } return allTF; } public static HashMap idf(HashMap&gt; all\_tf){ HashMap resIdf = new HashMap(); HashMap dict = new HashMap(); int docNum = FileList.size(); for(int i = 0; i &lt; docNum; i++){ HashMap temp = all\_tf.get(FileList.get(i)); Iterator iter = temp.entrySet().iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); String word = entry.getKey().toString(); if(dict.get(word) == null){ dict.put(word, 1); }else { dict.put(word, dict.get(word) + 1); } } } System.out.println("IDF for every word is:"); try { FileWriter writer = new FileWriter("d:\\\\IDF.txt", true); Iterator iter\_dict = dict.entrySet().iterator(); while(iter\_dict.hasNext()){ Map.Entry entry = (Map.Entry)iter\_dict.next(); float value = (float)Math.log(docNum / Float.parseFloat(entry.getValue().toString())); resIdf.put(entry.getKey().toString(), value); System.out.println(entry.getKey().toString() + " = " + value); writer.write(entry.getKey().toString() + " = " + value+"\\r\\n"); } writer.close(); } catch(Exception ex) { System.out.println("Error"); return null; } return resIdf; } public static void tf\_idf(HashMap&gt; all\_tf,HashMap idfs){ HashMap&gt; resTfIdf = new HashMap&gt;(); int docNum = FileList.size(); for(int i = 0; i &lt; docNum; i++){ String filepath = FileList.get(i); HashMap tfidf = new HashMap(); HashMap temp = all\_tf.get(filepath); Iterator iter = temp.entrySet().iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); String word = entry.getKey().toString(); Float value = (float)Float.parseFloat(entry.getValue().toString()) * idfs.get(word); tfidf.put(word, value); } resTfIdf.put(filepath, tfidf); } System.out.println("TF-IDF for Every file is :"); DisTfIdf(resTfIdf); } public static void DisTfIdf(HashMap&gt; tfidf){ Iterator iter1 = tfidf.entrySet().iterator(); try { FileWriter writer = new FileWriter("d:\\\\TF-IDF.txt", true); String strtemp=""; while(iter1.hasNext()){ Map.Entry entrys = (Map.Entry)iter1.next(); System.out.println("FileName: " + entrys.getKey().toString()); //writer.write("FileName: " + entrys.getKey().toString()); System.out.print("{"); writer.write("{"); HashMap temp = (HashMap) entrys.getValue(); Iterator iter2 = temp.entrySet().iterator(); while(iter2.hasNext()){ Map.Entry entry = (Map.Entry)iter2.next(); System.out.print(entry.getKey().toString() + " = " + entry.getValue().toString() + ", "); // 输出到文件 strtemp+=entry.getKey().toString() + " = " + entry.getValue().toString() + ", "; //writer.write(entry.getKey().toString() + " = " + entry.getValue().toString() + ", "); } strtemp=strtemp.substring(0, strtemp.length()-2); writer.write(strtemp); System.out.println("}"); writer.write("}"+"\\r\\n"); } writer.close(); } catch(Exception ex) { System.out.println("error!"); return; } } public static void main(String\[] args) throws IOException { // TODO Auto-generated method stub String file = "D:/testfiles"; HashMap&gt; all\_tf = tfAllFiles(file); System.out.println(); HashMap idfs = idf(all\_tf); System.out.println(); tf\_idf(all\_tf, idfs); } }