使用JAVA进行词频统计

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

               

在使用TF-IDF计算文章关键词的时候,需要知道某个词的词频是多少,使用 idf = Math.log(10000 + 10000.0 / (docFreq + 1))这个公式求解出idf的值。一般来说,词频统计越准确,每个词的idf的值就越准确,而词频的准确性与语料的多少有关,语料自然越多越好,但是通常情况下10G的数据量应该足够了。

假设现在我们有了10G的新闻语料和词列表,现在就可以来统计词频了,首先使用ANSJ对语料进行分词,分词时就把我们自定义的词列表作为用户字典,在得到分好词的数据后,再统计词频即可,JAVA代码如下:


import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class CalFreq static Map<String, Integer> map = new HashMap<String, Integer>(); public static void main(String[] args) throws IOException {  InputWord();  FileReader fr = new FileReader("resultbig.txt");  BufferedReader br = new BufferedReader(fr);  String line = "";  String outline[] = new String[2000];  int count;  int progress = 0;  while (line != null) {   line = br.readLine();   if (line == null) {    break;   }   //System.out.println(line);   progress++;   System.out.println("now is processing the " + progress + "'s news");   outline = line.split(" ", -1);   for (int i = 0; i < outline.length; i++) {    if (map.containsKey(outline[i]) != false) {     count = map.get(outline[i]) + 1;     map.put(outline[i], count);    }   }  }  fr.close();  br.close();  WriteWord(); } // put the word into the map public static void InputWord() throws IOException {  System.out.println("begin get the word");  FileReader fr = new FileReader("baike.txt");  BufferedReader br = new BufferedReader(fr);  String line = new String();  while (line != null) {   line = br.readLine();   if (line == null) {    break;   }   System.out.println(line);   map.put(line, 0);  }  br.close();  fr.close();  System.out.println("get the word is ok"); } // write word and frequency into the file public static void WriteWord() throws IOException {  System.out.println("begin write the word");  File file = new File("wordfreq.txt");  file.createNewFile();  FileWriter fw = new FileWriter("wordfreq.txt");  BufferedWriter bw = new BufferedWriter(fw);  for (Map.Entry<String, Integer> entry : map.entrySet()) {   String key = entry.getKey().toString();   int value = entry.getValue();   bw.write(key + " " + value);   bw.newLine();   bw.flush();  }  fw.close();  bw.close();  System.out.println("write the word is ok"); }}

这里baike.txt就是词表,resultbig.txt为使用ANSJ分好词的文本,wordfreq.txt即词表中的每个词出现的频率。

           

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值