生成文本聚类java实现 (1)

本文转自http://www.iteye.com/topic/989012

本文章纯属个人学习笔记,持续不断的增加中...

 

   本章主要的学习是中文分词两种统计词频(传统词频和TF-IDF算法 ) 的方法.

 

     学习目的:通过N多的新闻标题 or 新闻摘要 or 新闻标签,生成基本的文本聚类,以便统计当天新闻的热点内容.

     扩展:可以运用到文本分类 ,舆情分析 等.

 

     基本的学习思路:(本思路由网友rowen指点)

Java代码 复制代码  收藏代码
  1. 1.准备文本   
  2. 2.切词并统计词频   
  3. 3.去掉极低频词和无意义词(如这个、那个、等等)   
  4. 4.从剩余的词中提取文本特征,即最能代表文本的词   
  5. 5.用空间向量表示文本,空间向量需标准化,即将数值映射到-11之间   
  6. 6.利用所获取的空间向量进行聚类分析   
  7. 7.交叉验证  
1.准备文本
2.切词并统计词频
3.去掉极低频词和无意义词(如这个、那个、等等)
4.从剩余的词中提取文本特征,即最能代表文本的词
5.用空间向量表示文本,空间向量需标准化,即将数值映射到-1到1之间
6.利用所获取的空间向量进行聚类分析
7.交叉验证

    第一步,准备文本.

    我的做法是通过已经抓取好的RSS链接,然后通过Rome取得所有新闻数据,然后保存到MongoDb当中.这里叫奇的是MongoDb存取的速度哪叫一个惊人呀!哈哈.

    如下是代码片段,

Java代码 复制代码  收藏代码
  1. package com.antbee.test;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.FileReader;   
  5. import java.io.IOException;   
  6. import java.net.URL;   
  7. import java.util.List;   
  8. import java.util.Map;   
  9.   
  10. import org.junit.Test;   
  11.   
  12. import com.mongodb.BasicDBObject;   
  13. import com.sun.syndication.feed.synd.SyndEntry;   
  14. import com.sun.syndication.feed.synd.SyndFeed;   
  15. import com.sun.syndication.io.SyndFeedInput;   
  16. import com.sun.syndication.io.XmlReader;   
  17.   
  18. /**  
  19.  * @author Weiya He  
  20.  */  
  21. public class TestForFeedReader {   
  22.     static MongodService mongoDAO = new MongoServiceImpl("chinaRss""Rss");     
  23.     static String basepath = TestForMangoDb.class.getResource("/").getPath();   
  24.     @Test  
  25.     public void getDataFromRss() throws IOException {   
  26.         String filePath = basepath + "RSS.txt";     
  27.         FileReader fr = new FileReader(filePath);     
  28.         BufferedReader  br=new BufferedReader(fr);   
  29.         String rssUrl=br.readLine();   
  30.         SyndFeedInput input = new SyndFeedInput();     
  31.            
  32.         while (rssUrl != null) {   
  33.             System.out.println("正在分析网站:" + rssUrl);   
  34.             try {   
  35.                 SyndFeed feed = input.build(new XmlReader(new URL(rssUrl)));   
  36.                 List<SyndEntry> syndEntrys = feed.getEntries();   
  37.                 saveInDb(syndEntrys);   
  38.             } catch (Exception e) {   
  39.                 rssUrl = br.readLine();// 从文件中继续读取一行数据   
  40.             }   
  41.             rssUrl = br.readLine();// 从文件中继续读取一行数据   
  42.         }   
  43.         br.close();//关闭BufferedReader对象   
  44.         fr.close();//关闭文件    
  45.     }   
  46.     private void saveInDb(List<SyndEntry> syndEntrys){   
  47.         for (int i = 0; i < syndEntrys.size(); i++) {   
  48.             SyndEntry synd = syndEntrys.get(i);   
  49.             BasicDBObject val = new BasicDBObject();   
  50.             val.put("author", synd.getAuthor());   
  51.             val.put("contents",synd.getContents());   
  52.             val.put("description",synd.getDescription().toString());   
  53.             val.put("weblink",synd.getLink());   
  54.             val.put("publishedDate",synd.getPublishedDate());   
  55.             val.put("webSource",synd.getSource());   
  56.             val.put("title",synd.getTitle());   
  57.             val.put("updatedDate",synd.getUpdatedDate());   
  58.             val.put("url",synd.getUri());              
  59.             mongoDAO.getCollection().save(val);   
  60.         }   
  61.     }   
  62.     @Test  
  63.     public void findAll(){   
  64.         List<Map<String, Object>> map  = mongoDAO.findAll();   
  65.         for (int i=0;i<map.size();i++){   
  66.              Map<String, Object> m = map.get(i);             
  67.              System.out.println("title = "+m.get("title").toString().trim()+":::"+m.get("publishedDate"));   
  68.         }   
  69.            
  70.     }      
  71. }  
package com.antbee.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * @author Weiya He
 */
public class TestForFeedReader {
	static MongodService mongoDAO = new MongoServiceImpl("chinaRss", "Rss");  
	static String basepath = TestForMangoDb.class.getResource("/").getPath();
	@Test
	public void getDataFromRss() throws IOException {
		String filePath = basepath + "RSS.txt";  
		FileReader fr = new FileReader(filePath);  
		BufferedReader  br=new BufferedReader(fr);
		String rssUrl=br.readLine();
		SyndFeedInput input = new SyndFeedInput();	
		
		while (rssUrl != null) {
			System.out.println("正在分析网站:" + rssUrl);
			try {
				SyndFeed feed = input.build(new XmlReader(new URL(rssUrl)));
				List<SyndEntry> syndEntrys = feed.getEntries();
				saveInDb(syndEntrys);
			} catch (Exception e) {
				rssUrl = br.readLine();// 从文件中继续读取一行数据
			}
			rssUrl = br.readLine();// 从文件中继续读取一行数据
		}
		br.close();//关闭BufferedReader对象
		fr.close();//关闭文件 
	}
	private void saveInDb(List<SyndEntry> syndEntrys){
		for (int i = 0; i < syndEntrys.size(); i++) {
			SyndEntry synd = syndEntrys.get(i);
			BasicDBObject val = new BasicDBObject();
			val.put("author", synd.getAuthor());
			val.put("contents",synd.getContents());
			val.put("description",synd.getDescription().toString());
			val.put("weblink",synd.getLink());
			val.put("publishedDate",synd.getPublishedDate());
			val.put("webSource",synd.getSource());
			val.put("title",synd.getTitle());
			val.put("updatedDate",synd.getUpdatedDate());
			val.put("url",synd.getUri());			
			mongoDAO.getCollection().save(val);
		}
	}
	@Test
	public void findAll(){
		List<Map<String, Object>> map  = mongoDAO.findAll();
    	for (int i=0;i<map.size();i++){
    		 Map<String, Object> m = map.get(i);    		
    		 System.out.println("title = "+m.get("title").toString().trim()+":::"+m.get("publishedDate"));
    	}
		
	}	
}

 哈哈,通过如下方法把RSS的内容保存到MangoDb当中.

Java代码 复制代码  收藏代码
  1. getDataFromRss  
getDataFromRss

通过如下的方法,把数据库当中的数据取出来:

Java代码 复制代码  收藏代码
  1. findAll()  
 findAll()

哈哈,数据已经有了.如果觉得这样更新不及时的话,建议使用quartz加入你的应用调试吧,当然了这里只是实验代码,你应该加一些判断的逻辑在基中.

这是从抓取的部分RSS网址,大家可以下载试用.RSS.rar

 

第二步:切词并统计词频.

 

      切词当然用mmseg了,主要是网站对他的评论还行了.中科院的哪个配置太麻烦,封装的也不到位.呵呵.

      如下是代码片段:

Java代码 复制代码  收藏代码
  1. package com.antbee.cluster.wordCount;   
  2.   
  3. import java.io.ByteArrayInputStream;   
  4. import java.io.IOException;   
  5. import java.io.InputStreamReader;   
  6. import java.io.StringReader;   
  7. import java.util.Iterator;   
  8.   
  9. import org.junit.Test;   
  10.   
  11. import com.chenlb.mmseg4j.ComplexSeg;   
  12. import com.chenlb.mmseg4j.Dictionary;   
  13. import com.chenlb.mmseg4j.MMSeg;   
  14. import com.chenlb.mmseg4j.Seg;   
  15. import com.chenlb.mmseg4j.SimpleSeg;   
  16. import com.chenlb.mmseg4j.Word;   
  17.   
  18. /**  
  19.  *   
  20.  * @author Weiya  
  21.  * @version   
  22.  */  
  23. public class WordFrequencyStat {       
  24.   
  25.     @Test  
  26.     public void stat() throws IOException {   
  27.         String str = "昨日,中国人民银行宣布,自2011年4月6日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】";   
  28.         String text = this.segStr(str, "simple");//切词后结果   
  29.   
  30.         char[] w = new char[501];   
  31.         WordsTable wt = new WordsTable();   
  32.            
  33.         try {   
  34.             StringReader in = new StringReader(text);   
  35.             while (true) {   
  36.                 int ch = in.read();   
  37.                 if (Character.isLetter((char) ch)) {   
  38.                     int j = 0;   
  39.                     while (true) {   
  40.                         ch = Character.toLowerCase((char) ch);   
  41.                         w[j] = (char) ch;   
  42.                         if (j < 500)   
  43.                             j++;   
  44.                         ch = in.read();   
  45.                         if (!Character.isLetter((char) ch)) {   
  46.   
  47.                             String word1 = new String(w, 0, j);   
  48.   
  49.                             if (!wt.isStopWord(word1)) {// 如果不是停用词,则进行统计   
  50.                                 word1 = wt.getStem(word1);// 提取词干   
  51.                                 wt.stat(word1);   
  52.                             }   
  53.   
  54.                             break;   
  55.                         }   
  56.                     }   
  57.                 }   
  58.                 if (ch < 0)   
  59.                     break;   
  60.   
  61.             }   
  62.   
  63.             in.close();   
  64.             Iterator iter = wt.getWords();   
  65.             while (iter.hasNext()) {   
  66.                 WordCount wor = (WordCount) iter.next();   
  67.                 if (wor.getCount()>1){   
  68.                 System.out.println(wor.getWord() + "     :     " + wor.getCount());   
  69.                 }   
  70.             }              
  71.         } catch (Exception e) {   
  72.             System.out.println(e);   
  73.   
  74.         }   
  75.   
  76.     }   
  77.     /**  
  78.      *   
  79.      * @param text  
  80.      * @param mode: simple or complex  
  81.      * @return  
  82.      * @throws IOException   
  83.      */  
  84.     private String segStr(String text,String mode) throws IOException{   
  85.         String returnStr = "";   
  86.         Seg seg = null;   
  87.         Dictionary dic = Dictionary.getInstance();   
  88.         if ("simple".equals(mode)) {   
  89.             seg = new SimpleSeg(dic);   
  90.         } else {   
  91.             seg = new ComplexSeg(dic);   
  92.         }   
  93.   
  94.         // String words = seg.         
  95.         MMSeg mmSeg = new MMSeg(new InputStreamReader(new ByteArrayInputStream(text.getBytes())), seg);   
  96.         Word word = null;          
  97.         while ((word = mmSeg.next()) != null) {            
  98.             returnStr += word.getString()+" ";   
  99.         }          
  100.            
  101.         return returnStr;   
  102.     }   
  103. }  
package com.antbee.cluster.wordCount;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Iterator;

import org.junit.Test;

import com.chenlb.mmseg4j.ComplexSeg;
import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.MMSeg;
import com.chenlb.mmseg4j.Seg;
import com.chenlb.mmseg4j.SimpleSeg;
import com.chenlb.mmseg4j.Word;

/**
 * 
 * @author Weiya
 * @version 
 */
public class WordFrequencyStat {	

	@Test
	public void stat() throws IOException {
		String str = "昨日,中国人民银行宣布,自2011年4月6日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】";
		String text = this.segStr(str, "simple");//切词后结果

		char[] w = new char[501];
		WordsTable wt = new WordsTable();
		
		try {
			StringReader in = new StringReader(text);
			while (true) {
				int ch = in.read();
				if (Character.isLetter((char) ch)) {
					int j = 0;
					while (true) {
						ch = Character.toLowerCase((char) ch);
						w[j] = (char) ch;
						if (j < 500)
							j++;
						ch = in.read();
						if (!Character.isLetter((char) ch)) {

							String word1 = new String(w, 0, j);

							if (!wt.isStopWord(word1)) {// 如果不是停用词,则进行统计
								word1 = wt.getStem(word1);// 提取词干
								wt.stat(word1);
							}

							break;
						}
					}
				}
				if (ch < 0)
					break;

			}

			in.close();
			Iterator iter = wt.getWords();
			while (iter.hasNext()) {
				WordCount wor = (WordCount) iter.next();
				if (wor.getCount()>1){
				System.out.println(wor.getWord() + "     :     " + wor.getCount());
				}
			}			
		} catch (Exception e) {
			System.out.println(e);

		}

	}
	/**
	 * 
	 * @param text
	 * @param mode: simple or complex
	 * @return
	 * @throws IOException 
	 */
	private String segStr(String text,String mode) throws IOException{
		String returnStr = "";
		Seg seg = null;
		Dictionary dic = Dictionary.getInstance();
		if ("simple".equals(mode)) {
			seg = new SimpleSeg(dic);
		} else {
			seg = new ComplexSeg(dic);
		}

		// String words = seg.		
		MMSeg mmSeg = new MMSeg(new InputStreamReader(new ByteArrayInputStream(text.getBytes())), seg);
		Word word = null;		
		while ((word = mmSeg.next()) != null) {			
			returnStr += word.getString()+" ";
		}		
		
		return returnStr;
	}
}

注意代码:这是我写死了参数,如果出现频度大于1的才打印出来.

Java代码 复制代码  收藏代码
  1. if (wor.getCount()>1){   
  2.                 System.out.println(wor.getWord() + "     :     " + wor.getCount());   
  3.                 }  
if (wor.getCount()>1){
				System.out.println(wor.getWord() + "     :     " + wor.getCount());
				}

下面是打印出来的结果:

Java代码 复制代码  收藏代码
  1. 上调     :     2  
  2. 金融机构     :     2  
  3. 存贷     :     3  
  4. 款     :     3  
  5. 基准利率     :     3  
上调     :     2
金融机构     :     2
存贷     :     3
款     :     3
基准利率     :     3

 基本上能够算出词频来.

   继续。。。。

  但是从上面的词频的计算结果来说,也未必能够准确的表达文章的主旨,所以,我也在网上找了一个使用TFIDF算法来计算的词频,

  计算结果跟上面有很大不同。

  TF-IDF算法说明:

        TF-IDF(term frequency–inverse document frequency)。

        TFIDF的主要思想是:如果某个词或短语在一篇文章中出现的频率TF高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。TFIDF实际上是:TF*IDF,TF词频(Term Frequency),IDF反文档频率(Inverse Document Frequency)。TF表示词条t在文档d中出现的频率。IDF的主要思想是:如果包含词条t的文档越少,IDF越大,则说明词条t具有很好的类别区分能力。

 

代码如下:TfIdf.java

Java代码 复制代码  收藏代码
  1. package com.antbee.cluster.wordCount;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.ByteArrayInputStream;   
  5. import java.io.File;   
  6. import java.io.FileInputStream;   
  7. import java.io.FileNotFoundException;   
  8. import java.io.IOException;   
  9. import java.io.InputStreamReader;   
  10. import java.io.UnsupportedEncodingException;   
  11. import java.util.ArrayList;   
  12. import java.util.HashMap;   
  13. import java.util.List;   
  14. import java.util.Map;   
  15.   
  16. import org.junit.Test;   
  17.   
  18. import com.chenlb.mmseg4j.ComplexSeg;   
  19. import com.chenlb.mmseg4j.Dictionary;   
  20. import com.chenlb.mmseg4j.MMSeg;   
  21. import com.chenlb.mmseg4j.Seg;   
  22. import com.chenlb.mmseg4j.SimpleSeg;   
  23. import com.chenlb.mmseg4j.Word;   
  24.   
  25. public class TfIdf {   
  26.     private static List<String> fileList = new ArrayList<String>();   
  27.     private static HashMap<String, HashMap<String, Float>> allTheTf = new HashMap<String, HashMap<String, Float>>();   
  28.     private static HashMap<String, HashMap<String, Integer>> allTheNormalTF = new HashMap<String, HashMap<String, Integer>>();   
  29.   
  30.     public static List<String> readDirs(String filepath) throws FileNotFoundException, IOException {   
  31.         try {   
  32.             File file = new File(filepath);   
  33.             if (!file.isDirectory()) {   
  34.                 System.out.println("输入的参数应该为[文件夹名]");   
  35.                 System.out.println("filepath: " + file.getAbsolutePath());   
  36.             } else if (file.isDirectory()) {   
  37.                 String[] filelist = file.list();   
  38.                 for (int i = 0; i < filelist.length; i++) {   
  39.                     File readfile = new File(filepath + "\\" + filelist[i]);   
  40.                     if (!readfile.isDirectory()) {   
  41.                         // System.out.println("filepath: " +   
  42.                         // readfile.getAbsolutePath());   
  43.                         fileList.add(readfile.getAbsolutePath());   
  44.                     } else if (readfile.isDirectory()) {   
  45.                         readDirs(filepath + "\\" + filelist[i]);   
  46.                     }   
  47.                 }   
  48.             }   
  49.   
  50.         } catch (FileNotFoundException e) {   
  51.             System.out.println(e.getMessage());   
  52.         }   
  53.         return fileList;   
  54.     }   
  55.   
  56.     public static String readFiles(String file) throws FileNotFoundException, IOException {   
  57.         StringBuffer sb = new StringBuffer();   
  58.         InputStreamReader is = new InputStreamReader(new FileInputStream(file), "gbk");   
  59.         BufferedReader br = new BufferedReader(is);   
  60.         String line = br.readLine();   
  61.         while (line != null) {   
  62.             sb.append(line).append("\r\n");   
  63.             line = br.readLine();   
  64.         }   
  65.         br.close();   
  66.         return sb.toString();   
  67.     }   
  68.   
  69.     public static String[] cutWord(String file) throws IOException {   
  70.         String[] cutWordResult = null;   
  71.         String text = TfIdf.readFiles(file);   
  72.         //MMAnalyzer analyzer = new MMAnalyzer();   
  73.         // System.out.println("file content: "+text);   
  74.         // System.out.println("cutWordResult: "+analyzer.segment(text, " "));   
  75.         String tempCutWordResult = segStr(text, "simple");   
  76.         cutWordResult = tempCutWordResult.split(" ");   
  77.         return cutWordResult;   
  78.     }   
  79.     private static String segStr(String text,String mode) throws IOException{   
  80.         String returnStr = "";   
  81.         Seg seg = null;   
  82.         Dictionary dic = Dictionary.getInstance();   
  83.         if ("simple".equals(mode)) {   
  84.             seg = new SimpleSeg(dic);   
  85.         } else {   
  86.             seg = new ComplexSeg(dic);   
  87.         }   
  88.   
  89.         // String words = seg.         
  90.         MMSeg mmSeg = new MMSeg(new InputStreamReader(new ByteArrayInputStream(text.getBytes())), seg);   
  91.         Word word = null;          
  92.         while ((word = mmSeg.next()) != null) {            
  93.             returnStr += word.getString()+" ";   
  94.         }          
  95.            
  96.         return returnStr;   
  97.     }   
  98.   
  99.     public static HashMap<String, Float> tf(String[] cutWordResult) {   
  100.         HashMap<String, Float> tf = new HashMap<String, Float>();// 正规化   
  101.         int wordNum = cutWordResult.length;   
  102.         int wordtf = 0;   
  103.         for (int i = 0; i < wordNum; i++) {   
  104.             wordtf = 0;   
  105.             for (int j = 0; j < wordNum; j++) {   
  106.                 if (cutWordResult[i] != " " && i != j) {   
  107.                     if (cutWordResult[i].equals(cutWordResult[j])) {   
  108.                         cutWordResult[j] = " ";   
  109.                         wordtf++;   
  110.                     }   
  111.                 }   
  112.             }   
  113.             if (cutWordResult[i] != " ") {   
  114.                 tf.put(cutWordResult[i], (new Float(++wordtf)) / wordNum);   
  115.                 cutWordResult[i] = " ";   
  116.             }   
  117.         }   
  118.         return tf;   
  119.     }   
  120.   
  121.     public static HashMap<String, Integer> normalTF(String[] cutWordResult) {   
  122.         HashMap<String, Integer> tfNormal = new HashMap<String, Integer>();// 没有正规化   
  123.         int wordNum = cutWordResult.length;   
  124.         int wordtf = 0;   
  125.         for (int i = 0; i < wordNum; i++) {   
  126.             wordtf = 0;   
  127.             if (cutWordResult[i] != " ") {   
  128.                 for (int j = 0; j < wordNum; j++) {   
  129.                     if (i != j) {   
  130.                         if (cutWordResult[i].equals(cutWordResult[j])) {   
  131.                             cutWordResult[j] = " ";   
  132.                             wordtf++;   
  133.   
  134.                         }   
  135.                     }   
  136.                 }   
  137.                 tfNormal.put(cutWordResult[i], ++wordtf);   
  138.                 cutWordResult[i] = " ";   
  139.             }   
  140.         }   
  141.         return tfNormal;   
  142.     }   
  143.   
  144.     public static Map<String, HashMap<String, Float>> tfOfAll(String dir) throws IOException {   
  145.         List<String> fileList = TfIdf.readDirs(dir);   
  146.         for (String file : fileList) {   
  147.             HashMap<String, Float> dict = new HashMap<String, Float>();   
  148.             dict = TfIdf.tf(TfIdf.cutWord(file));   
  149.             allTheTf.put(file, dict);   
  150.         }   
  151.         return allTheTf;   
  152.     }   
  153.   
  154.     public static Map<String, HashMap<String, Integer>> NormalTFOfAll(String dir) throws IOException {   
  155.         List<String> fileList = TfIdf.readDirs(dir);   
  156.         for (int i = 0; i < fileList.size(); i++) {   
  157.             HashMap<String, Integer> dict = new HashMap<String, Integer>();   
  158.             dict = TfIdf.normalTF(TfIdf.cutWord(fileList.get(i)));   
  159.             allTheNormalTF.put(fileList.get(i), dict);   
  160.         }   
  161.         return allTheNormalTF;   
  162.     }   
  163.   
  164.     public static Map<String, Float> idf(String dir) throws FileNotFoundException, UnsupportedEncodingException,   
  165.             IOException {   
  166.         // 公式IDF=log((1+|D|)/|Dt|),其中|D|表示文档总数,|Dt|表示包含关键词t的文档数量。   
  167.         Map<String, Float> idf = new HashMap<String, Float>();   
  168.         List<String> located = new ArrayList<String>();   
  169.   
  170.         float Dt = 1;   
  171.         float D = allTheNormalTF.size();// 文档总数   
  172.         List<String> key = fileList;// 存储各个文档名的List   
  173.         Map<String, HashMap<String, Integer>> tfInIdf = allTheNormalTF;// 存储各个文档tf的Map   
  174.   
  175.         for (int i = 0; i < D; i++) {   
  176.             HashMap<String, Integer> temp = tfInIdf.get(key.get(i));   
  177.             for (String word : temp.keySet()) {   
  178.                 Dt = 1;   
  179.                 if (!(located.contains(word))) {   
  180.                     for (int k = 0; k < D; k++) {   
  181.                         if (k != i) {   
  182.                             HashMap<String, Integer> temp2 = tfInIdf.get(key.get(k));   
  183.                             if (temp2.keySet().contains(word)) {   
  184.                                 located.add(word);   
  185.                                 Dt = Dt + 1;   
  186.                                 continue;   
  187.                             }   
  188.                         }   
  189.                     }   
  190.                     idf.put(word, Log.log((1 + D) / Dt, 10));   
  191.                 }   
  192.             }   
  193.         }   
  194.         return idf;   
  195.     }   
  196.   
  197.     public static Map<String, HashMap<String, Float>> tfidf(String dir) throws IOException {   
  198.   
  199.         Map<String, Float> idf = TfIdf.idf(dir);   
  200.         Map<String, HashMap<String, Float>> tf = TfIdf.tfOfAll(dir);   
  201.   
  202.         for (String file : tf.keySet()) {   
  203.             Map<String, Float> singelFile = tf.get(file);   
  204.             for (String word : singelFile.keySet()) {   
  205.                 singelFile.put(word, (idf.get(word)) * singelFile.get(word));   
  206.             }   
  207.         }   
  208.         return tf;   
  209.     }   
  210.     @Test  
  211.     public void test() throws FileNotFoundException, UnsupportedEncodingException, IOException{   
  212.         Map<String, HashMap<String, Integer>> normal = TfIdf.NormalTFOfAll("d:/dir");   
  213.         for (String filename : normal.keySet()) {   
  214.             System.out.println("fileName " + filename);   
  215.             System.out.println("TF " + normal.get(filename).toString());   
  216.         }   
  217.   
  218.         System.out.println("-----------------------------------------");   
  219.   
  220.         Map<String, HashMap<String, Float>> notNarmal = TfIdf.tfOfAll("d:/dir");   
  221.         for (String filename : notNarmal.keySet()) {   
  222.             System.out.println("fileName " + filename);   
  223.             System.out.println("TF " + notNarmal.get(filename).toString());   
  224.         }   
  225.   
  226.         System.out.println("-----------------------------------------");   
  227.   
  228.         Map<String, Float> idf = TfIdf.idf("d;/dir");   
  229.         for (String word : idf.keySet()) {   
  230.             System.out.println("keyword :" + word + " idf: " + idf.get(word));   
  231.         }   
  232.   
  233.         System.out.println("-----------------------------------------");   
  234.   
  235.         Map<String, HashMap<String, Float>> tfidf = TfIdf.tfidf("d:/dir");   
  236.         for (String filename : tfidf.keySet()) {   
  237.             System.out.println("fileName " + filename);   
  238.             System.out.println(tfidf.get(filename));   
  239.         }   
  240.     }   
  241.        
  242. }  
package com.antbee.cluster.wordCount;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.chenlb.mmseg4j.ComplexSeg;
import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.MMSeg;
import com.chenlb.mmseg4j.Seg;
import com.chenlb.mmseg4j.SimpleSeg;
import com.chenlb.mmseg4j.Word;

public class TfIdf {
	private static List<String> fileList = new ArrayList<String>();
	private static HashMap<String, HashMap<String, Float>> allTheTf = new HashMap<String, HashMap<String, Float>>();
	private static HashMap<String, HashMap<String, Integer>> allTheNormalTF = new HashMap<String, HashMap<String, Integer>>();

	public static List<String> 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 if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "\\" + filelist[i]);
					if (!readfile.isDirectory()) {
						// System.out.println("filepath: " +
						// readfile.getAbsolutePath());
						fileList.add(readfile.getAbsolutePath());
					} else if (readfile.isDirectory()) {
						readDirs(filepath + "\\" + filelist[i]);
					}
				}
			}

		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		}
		return fileList;
	}

	public static String readFiles(String file) throws FileNotFoundException, IOException {
		StringBuffer sb = new StringBuffer();
		InputStreamReader is = new InputStreamReader(new FileInputStream(file), "gbk");
		BufferedReader br = new BufferedReader(is);
		String line = br.readLine();
		while (line != null) {
			sb.append(line).append("\r\n");
			line = br.readLine();
		}
		br.close();
		return sb.toString();
	}

	public static String[] cutWord(String file) throws IOException {
		String[] cutWordResult = null;
		String text = TfIdf.readFiles(file);
		//MMAnalyzer analyzer = new MMAnalyzer();
		// System.out.println("file content: "+text);
		// System.out.println("cutWordResult: "+analyzer.segment(text, " "));
		String tempCutWordResult = segStr(text, "simple");
		cutWordResult = tempCutWordResult.split(" ");
		return cutWordResult;
	}
	private static String segStr(String text,String mode) throws IOException{
		String returnStr = "";
		Seg seg = null;
		Dictionary dic = Dictionary.getInstance();
		if ("simple".equals(mode)) {
			seg = new SimpleSeg(dic);
		} else {
			seg = new ComplexSeg(dic);
		}

		// String words = seg.		
		MMSeg mmSeg = new MMSeg(new InputStreamReader(new ByteArrayInputStream(text.getBytes())), seg);
		Word word = null;		
		while ((word = mmSeg.next()) != null) {			
			returnStr += word.getString()+" ";
		}		
		
		return returnStr;
	}

	public static HashMap<String, Float> tf(String[] cutWordResult) {
		HashMap<String, Float> tf = new HashMap<String, Float>();// 正规化
		int wordNum = cutWordResult.length;
		int wordtf = 0;
		for (int i = 0; i < wordNum; i++) {
			wordtf = 0;
			for (int j = 0; j < wordNum; j++) {
				if (cutWordResult[i] != " " && i != j) {
					if (cutWordResult[i].equals(cutWordResult[j])) {
						cutWordResult[j] = " ";
						wordtf++;
					}
				}
			}
			if (cutWordResult[i] != " ") {
				tf.put(cutWordResult[i], (new Float(++wordtf)) / wordNum);
				cutWordResult[i] = " ";
			}
		}
		return tf;
	}

	public static HashMap<String, Integer> normalTF(String[] cutWordResult) {
		HashMap<String, Integer> tfNormal = new HashMap<String, Integer>();// 没有正规化
		int wordNum = cutWordResult.length;
		int wordtf = 0;
		for (int i = 0; i < wordNum; i++) {
			wordtf = 0;
			if (cutWordResult[i] != " ") {
				for (int j = 0; j < wordNum; j++) {
					if (i != j) {
						if (cutWordResult[i].equals(cutWordResult[j])) {
							cutWordResult[j] = " ";
							wordtf++;

						}
					}
				}
				tfNormal.put(cutWordResult[i], ++wordtf);
				cutWordResult[i] = " ";
			}
		}
		return tfNormal;
	}

	public static Map<String, HashMap<String, Float>> tfOfAll(String dir) throws IOException {
		List<String> fileList = TfIdf.readDirs(dir);
		for (String file : fileList) {
			HashMap<String, Float> dict = new HashMap<String, Float>();
			dict = TfIdf.tf(TfIdf.cutWord(file));
			allTheTf.put(file, dict);
		}
		return allTheTf;
	}

	public static Map<String, HashMap<String, Integer>> NormalTFOfAll(String dir) throws IOException {
		List<String> fileList = TfIdf.readDirs(dir);
		for (int i = 0; i < fileList.size(); i++) {
			HashMap<String, Integer> dict = new HashMap<String, Integer>();
			dict = TfIdf.normalTF(TfIdf.cutWord(fileList.get(i)));
			allTheNormalTF.put(fileList.get(i), dict);
		}
		return allTheNormalTF;
	}

	public static Map<String, Float> idf(String dir) throws FileNotFoundException, UnsupportedEncodingException,
			IOException {
		// 公式IDF=log((1+|D|)/|Dt|),其中|D|表示文档总数,|Dt|表示包含关键词t的文档数量。
		Map<String, Float> idf = new HashMap<String, Float>();
		List<String> located = new ArrayList<String>();

		float Dt = 1;
		float D = allTheNormalTF.size();// 文档总数
		List<String> key = fileList;// 存储各个文档名的List
		Map<String, HashMap<String, Integer>> tfInIdf = allTheNormalTF;// 存储各个文档tf的Map

		for (int i = 0; i < D; i++) {
			HashMap<String, Integer> temp = tfInIdf.get(key.get(i));
			for (String word : temp.keySet()) {
				Dt = 1;
				if (!(located.contains(word))) {
					for (int k = 0; k < D; k++) {
						if (k != i) {
							HashMap<String, Integer> temp2 = tfInIdf.get(key.get(k));
							if (temp2.keySet().contains(word)) {
								located.add(word);
								Dt = Dt + 1;
								continue;
							}
						}
					}
					idf.put(word, Log.log((1 + D) / Dt, 10));
				}
			}
		}
		return idf;
	}

	public static Map<String, HashMap<String, Float>> tfidf(String dir) throws IOException {

		Map<String, Float> idf = TfIdf.idf(dir);
		Map<String, HashMap<String, Float>> tf = TfIdf.tfOfAll(dir);

		for (String file : tf.keySet()) {
			Map<String, Float> singelFile = tf.get(file);
			for (String word : singelFile.keySet()) {
				singelFile.put(word, (idf.get(word)) * singelFile.get(word));
			}
		}
		return tf;
	}
	@Test
	public void test() throws FileNotFoundException, UnsupportedEncodingException, IOException{
		Map<String, HashMap<String, Integer>> normal = TfIdf.NormalTFOfAll("d:/dir");
        for (String filename : normal.keySet()) {
            System.out.println("fileName " + filename);
            System.out.println("TF " + normal.get(filename).toString());
        }

        System.out.println("-----------------------------------------");

        Map<String, HashMap<String, Float>> notNarmal = TfIdf.tfOfAll("d:/dir");
        for (String filename : notNarmal.keySet()) {
            System.out.println("fileName " + filename);
            System.out.println("TF " + notNarmal.get(filename).toString());
        }

        System.out.println("-----------------------------------------");

        Map<String, Float> idf = TfIdf.idf("d;/dir");
        for (String word : idf.keySet()) {
            System.out.println("keyword :" + word + " idf: " + idf.get(word));
        }

        System.out.println("-----------------------------------------");

        Map<String, HashMap<String, Float>> tfidf = TfIdf.tfidf("d:/dir");
        for (String filename : tfidf.keySet()) {
            System.out.println("fileName " + filename);
            System.out.println(tfidf.get(filename));
        }
    }
	
}

   Log.java

Java代码 复制代码  收藏代码
  1. public class Log {   
  2.     public static float log(float value, float base) {   
  3.         return (float) (Math.log(value) / Math.log(base));   
  4.     }   
  5. }  
public class Log {
	public static float log(float value, float base) {
        return (float) (Math.log(value) / Math.log(base));
    }
}

   其中我在d:盘下dir目录当中创建1.txt,文件为:

 

Java代码 复制代码  收藏代码
  1. 昨日,中国人民银行宣布,自201146日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率   
  2. 分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】  
昨日,中国人民银行宣布,自2011年4月6日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率
分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】
 

   通过TfIdf.java当中的测试类,结果为:

Java代码 复制代码  收藏代码
  1. fileName d:\dir\1.txt   
  2. TF {存款=1, 证券=1, 大=1, 公积金贷款=1, 而=1, 祥=1, 的=8, 可以=1, 工作日=1, 认为=1, 小说=1, 以来=1,   
  3.  对应=1, 其他=1, 斌=12011=1, 黄=1, 消化=1, 记者=1, 主要=2, 也=1, 比较=1, 军=2, 短期=1, 发展=1,    
  4. 年=1, 银行=1, 炒作=125=2, 分析=1, 市场=1, 档次=13=12=1, 这=10=16=231=14=1, 学院=1,    
  5. 人民币=1, 压力=28=1, 空间=1, 资本=1, 晚间=1, 为=1, 起到=1, 第二次=1, 次=1, 第四=1, 总体=3, 一年=3,   
  6.  部分=1, 主导=1, 对称=2, 较少=1, 个=1, 锡=2, 师=1, 达=1, 及=1, 投机=1, 利息=2, 调节=1, 百分点=1,    
  7. 款=3, 物价上涨=1, 开始=1, 副院长=1, 预期=1, 定期=1, 决定=1, 运作=1, 实体=1, 日=2, 与=2, 指出=1,    
  8. 利率=3, 将=1, 有帮助=1, 本报讯=1, 信=1, 上涨=1, 央行=1, 是=1, 个人住房=1, 资金=3, 抑制=1, 公告=1,    
  9. 用于=1, 倾向=1, 存贷=3, 今年以来=1, 相应=2, 上次=2, 有限=1, 保持=1, 去年=1, 操作=1, 长期=4, 上调=2,   
  10.  明=1, 期=3, 项目=1, 股份有限公司=1, 贷款=3, 投资=1, 生产=1, 整存=1, 明显=1, 月=2, 赵=2, 有=1,    
  11. 策略=1, 起=1, 可能=1, 幅度=2, 一样=1, 结束=1, 经济=1, 金融机构=2, 还有=1, 注意到=1, 发布=1, 加息=9,   
  12.  中国人民大学=1, 昨日=1, 增加=2, 价格=1, 分别=1, 之际=1, 缓解=1, 这是=1, 基准利率=3, 更多=1, 突然=1,   
  13.  作用=1, 中国人民银行=1, 整取=1, 导致=1, 假期=1, 也是=1, 流动资金=1, 企业=3, 平稳=1, 财=1, 后=1,    
  14. 利差=1, 金=1, 选择=1, 表示=1, 各=1, 涉及=1, 达到=2, 在=1, 首席=1, 本次=2, 对=1, 调整=2, 傍晚=1,   
  15.  宣布=1, 此次=1, 此外=1, 不同=1, 自=1}   
  16. -----------------------------------------   
  17. fileName d:\dir\1.txt   
  18. TF {存款=0.0044444446, 证券=0.0044444446, 大=0.0044444446, 公积金贷款=0.0044444446,    
  19. 而=0.0044444446, 祥=0.0044444446, 的=0.035555556, 可以=0.0044444446, 工作日=0.0044444446,    
  20. 认为=0.0044444446, 小说=0.0044444446, 以来=0.0044444446, 对应=0.0044444446,    
  21. 其他=0.0044444446, 斌=0.00444444462011=0.0044444446, 黄=0.0044444446,    
  22. 消化=0.0044444446, 记者=0.0044444446, 主要=0.008888889, 也=0.0044444446, 比较=0.0044444446,    
  23. 军=0.008888889, 短期=0.0044444446, 发展=0.0044444446, 年=0.0044444446, 银行=0.0044444446,    
  24. 炒作=0.004444444625=0.008888889, 分析=0.0044444446, 市场=0.0044444446, 档次=0.0044444446,   
  25.  3=0.00444444462=0.0044444446, 这=0.00444444460=0.00444444466=0.008888889,   
  26.  31=0.00444444464=0.0044444446, 学院=0.0044444446, 人民币=0.0044444446,   
  27.  压力=0.0088888898=0.0044444446, 空间=0.0044444446, 资本=0.0044444446, 晚间=0.0044444446,   
  28.  为=0.0044444446, 起到=0.0044444446, 第二次=0.0044444446, 次=0.0044444446, 第四=0.0044444446,   
  29.  总体=0.013333334, 一年=0.013333334, 部分=0.0044444446, 主导=0.0044444446, 对称=0.008888889,   
  30.  较少=0.0044444446, 个=0.0044444446, 锡=0.008888889, 师=0.0044444446, 达=0.0044444446,   
  31.  及=0.0044444446, 投机=0.0044444446, 利息=0.008888889, 调节=0.0044444446,    
  32. 百分点=0.0044444446, 款=0.013333334, 物价上涨=0.0044444446, 开始=0.0044444446,    
  33. 副院长=0.0044444446, 预期=0.0044444446, 定期=0.0044444446, 决定=0.0044444446,    
  34. 运作=0.0044444446, 实体=0.0044444446, 日=0.008888889, 与=0.008888889, 指出=0.0044444446,   
  35.  利率=0.013333334, 将=0.0044444446, 有帮助=0.0044444446, 本报讯=0.0044444446,    
  36. 信=0.0044444446, 上涨=0.0044444446, 央行=0.0044444446, 是=0.0044444446,    
  37. 个人住房=0.0044444446, 资金=0.013333334, 抑制=0.0044444446, 公告=0.0044444446,    
  38. 用于=0.0044444446, 倾向=0.0044444446, 存贷=0.013333334, 今年以来=0.0044444446,    
  39. 相应=0.008888889, 上次=0.008888889, 有限=0.0044444446, 保持=0.0044444446, 去年=0.0044444446,    
  40. 操作=0.0044444446, 长期=0.017777778, 上调=0.008888889, 明=0.0044444446, 期=0.013333334,    
  41. 项目=0.0044444446, 股份有限公司=0.0044444446, 贷款=0.013333334, 投资=0.0044444446,    
  42. 生产=0.0044444446, 整存=0.0044444446, 明显=0.0044444446, 月=0.008888889, 赵=0.008888889,    
  43. 有=0.0044444446, 策略=0.0044444446, 起=0.0044444446, 可能=0.0044444446, 幅度=0.008888889,    
  44. 一样=0.0044444446, 结束=0.0044444446, 经济=0.0044444446, 金融机构=0.008888889,    
  45. 还有=0.0044444446, 注意到=0.0044444446, 发布=0.0044444446, 加息=0.04,    
  46. 中国人民大学=0.0044444446, 昨日=0.0044444446, 增加=0.008888889, 价格=0.0044444446,    
  47. 分别=0.0044444446, 之际=0.0044444446, 缓解=0.0044444446, 这是=0.0044444446,    
  48. 基准利率=0.013333334, 更多=0.0044444446, 突然=0.0044444446, 作用=0.0044444446,    
  49. 中国人民银行=0.0044444446, 整取=0.0044444446, 导致=0.0044444446, 假期=0.0044444446,   
  50.  也是=0.0044444446, 流动资金=0.0044444446, 企业=0.013333334, 平稳=0.0044444446,   
  51.  财=0.0044444446, 后=0.0044444446, 利差=0.0044444446, 金=0.0044444446, 选择=0.0044444446,   
  52.  表示=0.0044444446, 各=0.0044444446, 涉及=0.0044444446, 达到=0.008888889, 在=0.0044444446,    
  53. 首席=0.0044444446, 本次=0.008888889, 对=0.0044444446, 调整=0.008888889, 傍晚=0.0044444446,    
  54. 宣布=0.0044444446, 此次=0.0044444446, 此外=0.0044444446, 不同=0.0044444446, 自=0.0044444446}   
  55. -----------------------------------------   
  56. keyword :存款 idf: 0.30103  
  57. keyword :公积金贷款 idf: 0.30103  
  58. keyword :大 idf: 0.30103  
  59. keyword :证券 idf: 0.30103  
fileName d:\dir\1.txt
TF {存款=1, 证券=1, 大=1, 公积金贷款=1, 而=1, 祥=1, 的=8, 可以=1, 工作日=1, 认为=1, 小说=1, 以来=1,
 对应=1, 其他=1, 斌=1, 2011=1, 黄=1, 消化=1, 记者=1, 主要=2, 也=1, 比较=1, 军=2, 短期=1, 发展=1, 
年=1, 银行=1, 炒作=1, 25=2, 分析=1, 市场=1, 档次=1, 3=1, 2=1, 这=1, 0=1, 6=2, 31=1, 4=1, 学院=1, 
人民币=1, 压力=2, 8=1, 空间=1, 资本=1, 晚间=1, 为=1, 起到=1, 第二次=1, 次=1, 第四=1, 总体=3, 一年=3,
 部分=1, 主导=1, 对称=2, 较少=1, 个=1, 锡=2, 师=1, 达=1, 及=1, 投机=1, 利息=2, 调节=1, 百分点=1, 
款=3, 物价上涨=1, 开始=1, 副院长=1, 预期=1, 定期=1, 决定=1, 运作=1, 实体=1, 日=2, 与=2, 指出=1, 
利率=3, 将=1, 有帮助=1, 本报讯=1, 信=1, 上涨=1, 央行=1, 是=1, 个人住房=1, 资金=3, 抑制=1, 公告=1, 
用于=1, 倾向=1, 存贷=3, 今年以来=1, 相应=2, 上次=2, 有限=1, 保持=1, 去年=1, 操作=1, 长期=4, 上调=2,
 明=1, 期=3, 项目=1, 股份有限公司=1, 贷款=3, 投资=1, 生产=1, 整存=1, 明显=1, 月=2, 赵=2, 有=1, 
策略=1, 起=1, 可能=1, 幅度=2, 一样=1, 结束=1, 经济=1, 金融机构=2, 还有=1, 注意到=1, 发布=1, 加息=9,
 中国人民大学=1, 昨日=1, 增加=2, 价格=1, 分别=1, 之际=1, 缓解=1, 这是=1, 基准利率=3, 更多=1, 突然=1,
 作用=1, 中国人民银行=1, 整取=1, 导致=1, 假期=1, 也是=1, 流动资金=1, 企业=3, 平稳=1, 财=1, 后=1, 
利差=1, 金=1, 选择=1, 表示=1, 各=1, 涉及=1, 达到=2, 在=1, 首席=1, 本次=2, 对=1, 调整=2, 傍晚=1,
 宣布=1, 此次=1, 此外=1, 不同=1, 自=1}
-----------------------------------------
fileName d:\dir\1.txt
TF {存款=0.0044444446, 证券=0.0044444446, 大=0.0044444446, 公积金贷款=0.0044444446, 
而=0.0044444446, 祥=0.0044444446, 的=0.035555556, 可以=0.0044444446, 工作日=0.0044444446, 
认为=0.0044444446, 小说=0.0044444446, 以来=0.0044444446, 对应=0.0044444446, 
其他=0.0044444446, 斌=0.0044444446, 2011=0.0044444446, 黄=0.0044444446, 
消化=0.0044444446, 记者=0.0044444446, 主要=0.008888889, 也=0.0044444446, 比较=0.0044444446, 
军=0.008888889, 短期=0.0044444446, 发展=0.0044444446, 年=0.0044444446, 银行=0.0044444446, 
炒作=0.0044444446, 25=0.008888889, 分析=0.0044444446, 市场=0.0044444446, 档次=0.0044444446,
 3=0.0044444446, 2=0.0044444446, 这=0.0044444446, 0=0.0044444446, 6=0.008888889,
 31=0.0044444446, 4=0.0044444446, 学院=0.0044444446, 人民币=0.0044444446,
 压力=0.008888889, 8=0.0044444446, 空间=0.0044444446, 资本=0.0044444446, 晚间=0.0044444446,
 为=0.0044444446, 起到=0.0044444446, 第二次=0.0044444446, 次=0.0044444446, 第四=0.0044444446,
 总体=0.013333334, 一年=0.013333334, 部分=0.0044444446, 主导=0.0044444446, 对称=0.008888889,
 较少=0.0044444446, 个=0.0044444446, 锡=0.008888889, 师=0.0044444446, 达=0.0044444446,
 及=0.0044444446, 投机=0.0044444446, 利息=0.008888889, 调节=0.0044444446, 
百分点=0.0044444446, 款=0.013333334, 物价上涨=0.0044444446, 开始=0.0044444446, 
副院长=0.0044444446, 预期=0.0044444446, 定期=0.0044444446, 决定=0.0044444446, 
运作=0.0044444446, 实体=0.0044444446, 日=0.008888889, 与=0.008888889, 指出=0.0044444446,
 利率=0.013333334, 将=0.0044444446, 有帮助=0.0044444446, 本报讯=0.0044444446, 
信=0.0044444446, 上涨=0.0044444446, 央行=0.0044444446, 是=0.0044444446, 
个人住房=0.0044444446, 资金=0.013333334, 抑制=0.0044444446, 公告=0.0044444446, 
用于=0.0044444446, 倾向=0.0044444446, 存贷=0.013333334, 今年以来=0.0044444446, 
相应=0.008888889, 上次=0.008888889, 有限=0.0044444446, 保持=0.0044444446, 去年=0.0044444446, 
操作=0.0044444446, 长期=0.017777778, 上调=0.008888889, 明=0.0044444446, 期=0.013333334, 
项目=0.0044444446, 股份有限公司=0.0044444446, 贷款=0.013333334, 投资=0.0044444446, 
生产=0.0044444446, 整存=0.0044444446, 明显=0.0044444446, 月=0.008888889, 赵=0.008888889, 
有=0.0044444446, 策略=0.0044444446, 起=0.0044444446, 可能=0.0044444446, 幅度=0.008888889, 
一样=0.0044444446, 结束=0.0044444446, 经济=0.0044444446, 金融机构=0.008888889, 
还有=0.0044444446, 注意到=0.0044444446, 发布=0.0044444446, 加息=0.04, 
中国人民大学=0.0044444446, 昨日=0.0044444446, 增加=0.008888889, 价格=0.0044444446, 
分别=0.0044444446, 之际=0.0044444446, 缓解=0.0044444446, 这是=0.0044444446, 
基准利率=0.013333334, 更多=0.0044444446, 突然=0.0044444446, 作用=0.0044444446, 
中国人民银行=0.0044444446, 整取=0.0044444446, 导致=0.0044444446, 假期=0.0044444446,
 也是=0.0044444446, 流动资金=0.0044444446, 企业=0.013333334, 平稳=0.0044444446,
 财=0.0044444446, 后=0.0044444446, 利差=0.0044444446, 金=0.0044444446, 选择=0.0044444446,
 表示=0.0044444446, 各=0.0044444446, 涉及=0.0044444446, 达到=0.008888889, 在=0.0044444446, 
首席=0.0044444446, 本次=0.008888889, 对=0.0044444446, 调整=0.008888889, 傍晚=0.0044444446, 
宣布=0.0044444446, 此次=0.0044444446, 此外=0.0044444446, 不同=0.0044444446, 自=0.0044444446}
-----------------------------------------
keyword :存款 idf: 0.30103
keyword :公积金贷款 idf: 0.30103
keyword :大 idf: 0.30103
keyword :证券 idf: 0.30103
 

   从上面的结果来说,两个不同的算法大相径庭,我想可能要更多的测试才能得到结论。

 

    第三步 去掉极低频词和无意义词(如这个、那个、等等)

 

   可以将在单一文本中只出现1,2次的词去掉,

   然后需要在网上下载一个中文停用词表,去掉文本中的停用词,即无意义词
 好了,下一节将学习和研究使用KNN或者SVM提取特征词。
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值