java 词频统计_词频统计的java实现方法——第一次改进

该博客详细介绍了如何用Java实现词频统计,包括从命令行读取文本、文件输入、文件夹批量统计以及输出到文件的功能。程序通过main函数接收参数,使用BufferedReader进行缓冲读取,处理不同输入源,支持纯英文单词和字母开头夹杂数字的单词统计。同时,提供了多文件读取和输出到指定文件的选项。
摘要由CSDN通过智能技术生成

需求概要

原需求

1.读取文件,文件内包可含英文字符,及常见标点,空格级换行符。

2.统计英文单词在本文件的出现次数

3.将统计结果排序

4.显示排序结果

新需求:

1.小文件输入. 为表明程序能跑

2.支持命令行输入英文作品的文件名

3. 支持命令行输入存储有英文作品文件的目录名,批量统计。

4. 从控制台读入英文单篇作品

程序输入:

1.控制台输入文本

2.英文文本文件

3.英文目录,目录下包含单个或多个英文文本文件

程序输出:

1.英文单词在本文件或控制台输入中的出现的次数,按出现次数排序

2.文本或控制台输入文字的单词数和不重复单词数

输出位置:

控制台或指定文件

支持统计的词包括:纯英文单词和字母开头夹杂数字的单词,例如:happy,x11,i386,w3c等

程序的使用设计

1.程序直接运行,不加参数,则进入标准输入状态,所有标准输入作为词频统计分析的内容,windows下回车加ctrl+Z作为退出输入模式的出口,然后对输入缓存进行统计

2.使用选项参数

默认情况下接受文件名或文件夹作为输入,读入单独或文件夹下的多个文件

-o可以指定输出文件名,即保存统计结果到文件中,不适用-o选项则将输出结果打印到终端或控制台,

-s出现此选项则将之后的输入视为标准输入,作为分析的内容。

主要功能设计和分析

前一部分的内容不在此赘述,以下为更新后的功能设计

不同输入逻辑处理

根据最新需求,本程序需要处理来自文本和控制台的输入,需要对程序运行的参数和方法进行控制,java程序的main函数String[] args可以接收程序运行的参数,当参数为空时则进入标准输入读入的模式,有参数的时候根据不同参数进行操作。

为简化逻辑,参数的读入和初始化可以建立初始化器来使用的参数进行环境设置或者初始化,main函数中则根据已经设定好的环境来决定从哪读入向哪输出。

缓冲读取文件或标准输入流,统计词频

当程序参数为空时需要将标准输入作为待分析内容,java提供的System.in可作为标准输入,读入时可以使用byte[]来接收。

当程序读入文件时可以使用char[]来接收读取到的内容,这与标准输入流略有不同,不过可以通过类型转换的方式来实现重用。

词频统计与之前的区别在于,使用BufferedReader提供的read来替换readline来解决当行过长导致的字符串溢出问题,这样就需要定义一个缓冲区来分块读取文件或输入流的内容,读取到的缓冲区再模仿状态机的处理方式来确定读入的字符该如何处理

多文件的读取

java文件类提供判断一个路径是不是文件夹的函数即File.isDirectory(),如果确定输入为文件夹则使用File.listFiles()获取到文件夹下的所有文件,然后循环分析词频,根据已经创建好的环境决定输出到文件还是控制台。

部分代码实现

初始化器实现

1 String inputFile = null;2 String outputFile = null;3 boolean stdin = false;4

5 private booleansetArgs(String[] args) {6 try{7 if (args.length == 0) {8 stdin=true;9 return true;10 }11 boolean isOption = false;12 for (int i = 0; i < args.length; i++) {13 if (args[i].startsWith("-")) {14 isOption = true;15 if (args[i].equals("-o")) {16 outputFile = args[i + 1];17 } else if(args.equals("-s")){18 stdin = true;19 return true;20 }else{21 System.out.println("unknow commend:" +args[i]);22 return false;23 }24 } else if(isOption) {25 //setOpetion

26 isOption = false;27 } else if (inputFile == null) {28 inputFile =args[i];29 } else{30 System.out.println("wrong command");31 return false;32 }33 }34 System.out.println("inputfile = " +inputFile);35 System.out.println("onputfile = " +outputFile);36 if (inputFile == null) {37 System.out.println("no input file name");38 return false;39 }40 } catch(Exception e) {41 System.out.println("wrong command");42 return false;43 }44 return true;45 }

更新后的词频统计

文件方式作为输入

1 public MapgetWordGroupCountBuffered(String filename) {2 try{3 FileReader fr = newFileReader(filename);4 BufferedReader br = newBufferedReader(fr);5 StringBuffer content = new StringBuffer("");6 Map result = new HashMap();7 char[] ch = new char[64];8 int bs = 0;9 intidx;10 boolean added = false;11 total = 0;12 while ((bs = br.read(ch)) > 0) {13 for (idx = 0; idx < bs; idx++) {14 if (isCharacter(ch[idx])==1) {15 content.append(ch[idx]);16 added = false;17 } else if(isCharacter(ch[idx])==2){18 if(added == true){19 continue;20 }else{21 content.append(ch[idx]);22 }23 } else{24 if(added==true){25 continue;26 }27 added = true;28 if(content.equals(""))29 continue;30 String key =content.toString();31 if(result.containsKey(key))32 result.put(key, result.get(key) + 1);33 else

34 result.put(key, 1);35 total++;36 content = new StringBuffer("");37 continue;38 }39

40 }41 }42 br.close();43 fr.close();44 returnresult;45 } catch(FileNotFoundException e) {46 System.out.println("failed to open file:" +filename);47 e.printStackTrace();48 } catch(Exception e) {49 System.out.println("some expection occured");50 e.printStackTrace();51 }52 return null;53 }

标准输入作为输入

1 public MapgetWordGroupCountBuffered(InputStream in) {2 try{3 StringBuffer content = new StringBuffer("");4 Map result = new HashMap();5 byte[] bt = new byte[128];6 char [] ch = new char[64];7 int bs = 0;8 intidx;9 int cs = 0;10 boolean added = false;11 total = 0;12 while ((bs = in.read(bt)) > 0) {13 ch =byteToChar(bt,bs);14 cs =bs;15 for (idx = 0; idx < cs; idx++) {16 if (isCharacter(ch[idx])==1) {17 content.append(ch[idx]);18 added = false;19 } else if(isCharacter(ch[idx])==2){20 if(added == true){21 continue;22 }else{23 content.append(ch[idx]);24 }25 } else{26 if(added==true){27 continue;28 }29 added = true;30 if(content.equals(""))31 continue;32 String key =content.toString();33 if(result.containsKey(key))34 result.put(key, result.get(key) + 1);35 else

36 result.put(key, 1);37 total++;38 content = new StringBuffer("");39 continue;40 }41

42 }43 }44 returnresult;45 } catch(Exception e) {46 System.out.println("some expection occured");47 e.printStackTrace();48 }49 return null;50 }

文件夹下多文件统计函数头为

1 public void printSortedWordGroupCountToFileBuffered(File[] files, String destinationFilename)

实现方式基本同单个文件统计方式,仅需添加循环遍历和输出文件方式设定为追加,并且第一次打开时清空文件内容,防止多次执行同一命令时重复追加到一个文件。

主函数逻辑控制

1 public static voidmain(String[] args) {2 RunFileWordUtil rfu = newRunFileWordUtil();3 if (!rfu.setArgs(args)) {4 return;5 }6 File f = null;7 FileWordUtil fu = newFileWordUtil();8 if(rfu.stdin){9 fu.printSortedWordGroupCountBuffered(System.in);10 }else{11 f = newFile(rfu.inputFile);12 if(f.isDirectory()){13 File[] files =f.listFiles();14 if(rfu.outputFile == null){15 System.err.println("warning : print to console is not recomanded");16 fu.printSortedWordGroupCountBuffered(files);17 }else{18 fu.printSortedWordGroupCountToFileBuffered(files,rfu.outputFile);19 }20 }else if (rfu.outputFile == null) {21 System.err.println("warning : print to console is not recomand");22 fu.printSortedWordGroupCountBuffered(rfu.inputFile);23 }else{24 fu.printSortedWordGroupCountToFileBuffered(rfu.inputFile, rfu.outputFile);25 }26 }27 }

其他被调用的部分自定义函数

1 private int isCharacter(charch) {2 if ((ch >= 'a' && ch <= 'z'))3 return 1;4 if((ch >= 'A' && ch <= 'Z'))5 return 1;6 if(ch>='0'&&ch<='9')7 return 2;8 return 0;9 }10

11 private char[] byteToChar(byte[] bt,intlength){12 char[] ch = new char[length];13 for(int i=0;i

实际运行结果

1.标准输入作为输入内容

89281e94d92b37cb41b9b1f02acea501.png

2.单个文件作为输入内容

文件内容:

hello world

this is a

what a sunny day!

do

you

have a cup?

read the book

My English is very very pool.

warning为标准错误输出,在支持彩色显示的终端中可以显示为红色(或其他自定义颜色)

2d7f7d1f41f6b94be2375a1cd4e672ab.png

3.文件夹下的所有文件作为输入内容

3de3f4c556273c13fb90fa7cf4849292.png

4.结果输出到文件

4b2f1c7b11765f9be6ad4dc8bbdced8b.png

5.大文件统计:

文件内容:英文版WarandPeace.txt

48cbc808f1b637b7205d933d4eabf658.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值