本文转自http://www.iteye.com/topic/989012
本文章纯属个人学习笔记,持续不断的增加中...
本章主要的学习是中文分词 和两种统计词频(传统词频和TF-IDF算法 ) 的方法.
学习目的:通过N多的新闻标题 or 新闻摘要 or 新闻标签,生成基本的文本聚类,以便统计当天新闻的热点内容.
扩展:可以运用到文本分类 ,舆情分析 等.
基本的学习思路:(本思路由网友rowen指点)
- 1.准备文本
- 2.切词并统计词频
- 3.去掉极低频词和无意义词(如这个、那个、等等)
- 4.从剩余的词中提取文本特征,即最能代表文本的词
- 5.用空间向量表示文本,空间向量需标准化,即将数值映射到-1到1之间
- 6.利用所获取的空间向量进行聚类分析
- 7.交叉验证
1.准备文本
2.切词并统计词频
3.去掉极低频词和无意义词(如这个、那个、等等)
4.从剩余的词中提取文本特征,即最能代表文本的词
5.用空间向量表示文本,空间向量需标准化,即将数值映射到-1到1之间
6.利用所获取的空间向量进行聚类分析
7.交叉验证
第一步,准备文本.
我的做法是通过已经抓取好的RSS链接,然后通过Rome取得所有新闻数据,然后保存到MongoDb当中.这里叫奇的是MongoDb存取的速度哪叫一个惊人呀!哈哈.
如下是代码片段,
- 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"));
- }
- }
- }
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当中.
- getDataFromRss
getDataFromRss
通过如下的方法,把数据库当中的数据取出来:
- findAll()
findAll()
哈哈,数据已经有了.如果觉得这样更新不及时的话,建议使用quartz加入你的应用调试吧,当然了这里只是实验代码,你应该加一些判断的逻辑在基中.
这是从抓取的部分RSS网址,大家可以下载试用.RSS.rar
第二步:切词并统计词频.
切词当然用mmseg了,主要是网站对他的评论还行了.中科院的哪个配置太麻烦,封装的也不到位.呵呵.
如下是代码片段:
- 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;
- }
- }
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的才打印出来.
- if (wor.getCount()>1){
- System.out.println(wor.getWord() + " : " + wor.getCount());
- }
if (wor.getCount()>1){
System.out.println(wor.getWord() + " : " + wor.getCount());
}
下面是打印出来的结果:
- 上调 : 2
- 金融机构 : 2
- 存贷 : 3
- 款 : 3
- 基准利率 : 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
- 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));
- }
- }
- }
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
- public class Log {
- public static float log(float value, float base) {
- return (float) (Math.log(value) / Math.log(base));
- }
- }
public class Log {
public static float log(float value, float base) {
return (float) (Math.log(value) / Math.log(base));
}
}
其中我在d:盘下dir目录当中创建1.txt,文件为:
- 昨日,中国人民银行宣布,自2011年4月6日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率
- 分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】
昨日,中国人民银行宣布,自2011年4月6日起上调金融机构人民币存贷款基准利率。金融机构一年期存贷款基准利率
分别上调0.25个百分点,其他各档次存贷款基准利率及个人住房公积金贷款利率相应调整。【加息前后房贷对比图】
通过TfIdf.java当中的测试类,结果为:
- 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
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次的词去掉,