Java:词频统计程序

                                                          词频统计程序(Java)

题目描述:

       做一个词频统计程序,该程序具有以下功能:
        基本要求:
     (1)可导入任意英文文本文件
     (2)统计该英文文件中单词数和各单词出现的频率(次数),并能将单词按字典顺序输出。
     (3)将单词及频率写入文件。

        提高要求:

     (4)将单词及频率写入数据库。

具体实现代码如下(不包括DAO部分):

package com._520it._chapter02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com._520it._chapter02.dao.IWordDAO;
import com._520it._chapter02.dao.impl.WordDAOImpl;
import com._520it._chapter02.domain.Word;

/**
 * 词频统计程序
 * @author Jack
 * @date 2018-09-21
 * @version 1.0
 */
public class WordCounts {

	public static void main(String[] args) {
		// 从文件中读取数据,并存入List集合中
		List<String> list = readFromFile();
		String str = list.get(0);
		str.replaceAll(",", "");
		str.replaceAll(".", "");
		String[] words = str.split(" ");
		// 将单词全部转换为小写
		for (int i = 0; i < words.length; i++) {
			words[i] = words[i].toLowerCase();
		}
		// 将单词按照字典排序
		words = sortWords(words);
		// 将结果放入Map集合中
		Map<String, Integer> map = new HashMap<>();
		for (int i = 0; i < words.length; i++) {
			if (!map.containsKey(words[i])) {
				map.put(words[i], 1);
			} else {
				int num = map.get(words[i]) + 1;
				map.put(words[i], num);
			}
		}
		// 将结果写入文件
		writeToFile(map);
		Iterator<String> iterator = map.keySet().iterator();
		IWordDAO dao = new WordDAOImpl();
		while (iterator.hasNext()) {
			Word w = new Word();
			String word = (String) iterator.next();
			w.setWord(word);
			w.setCount(map.get(word).longValue());
			// 将结果写入数据库
			dao.save(w);
		}
	}

	/**
	 * 从文件中读取数据
	 * @return 存有数据的List集合
	 */
	private static List<String> readFromFile() {
		// 表示读取的行
		String line = null;
		List<String> list = new ArrayList<>();
		try {
			// 创建字符输入流对象
			FileReader srcFile = new FileReader("resources/data.txt");
			// 字符缓冲输入流
			BufferedReader in = new BufferedReader(srcFile);
			while ((line = in.readLine()) != null) {
				// 将数据存储到list集合中
				list.add(line);
			}
			// 关闭资源
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 将结果写入文件
	 * @param map Map集合
	 */
	private static void writeToFile(Map<String, Integer> map) {
		try {
			// 创建字符输出流对象
			FileWriter desFile = new FileWriter("resources/result.txt", true);
			// 字符缓冲输出流
			BufferedWriter out = new BufferedWriter(desFile);
			Iterator<String> iterator = map.keySet().iterator();
			while (iterator.hasNext()) {
				String word = (String) iterator.next();
				out.write(word + " : " + map.get(word));
				// 输出换行
				out.newLine();
			}
			// 关闭资源
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将字符串数组按照字典排序
	 * @param str 需要排序的数组
	 * @return 排序后的字符串数组
	 */
	private static String[] sortWords(String[] str) {
		for (int i = 0; i < str.length - 1; i++) {
			for (int j = 0; j < str.length - 1 - i; j++) {
				if ((str[j].compareTo(str[j + 1])) > 0) {
					String temp = str[j];
					str[j] = str[j + 1];
					str[j + 1] = temp;
				}
			}
		}
		return str;
	}
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,词频统计是一个非常经典的MapReduce程序案例。下面是一份Java代码示例: ``` public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{ private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 在这个示例中,Mapper将输入文本分割成单词,并且将每个单词映射为键值对(单词,1)。然后,Combiner将相同单词的键值对合并起来,并且将它们的值相加。最后,Reducer将每个单词的总和输出为键值对(单词,总和)。在MapReduce执行过程中,Hadoop会自动将数据分割为若干个等大小的块,并行处理这些块,最终将它们的结果合并输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值