一、目的
计算某个词出现频率,可以很好的对一篇文章水平的评价提供客观依据,比如在技术类文章中出现“的”字的频率太高,说明此文章逻辑不够严谨,本次应用程序的目的就是计算出指定文本中指定词出现的频率。
二、程序演示
- 有如下一个文本文件
w.txt
,我们计算“的”字出现的频率。
“的”出现的频率为:3/35=8%。 - 应用程序计算“的”字出现的频率。
观察可以看出计算结果一致。
三、源码
【ScanWords.java】
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.NumberFormat;
import java.util.Scanner;
public class ScanWords {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String BookName;
String txt = null;
String in = null;
boolean flag = true;
long count = 0;
long all = 0;
System.out.println("请录入检索文本:");
Scanner scan1 = new Scanner(System.in);
BookName = scan1.nextLine();
File file = new File(BookName);
if(!(file.exists())){ //利用exits()函数查看文本是否存在
System.out.println("\n"+file.getName()+ "不存在");
System.exit(0);
}
System.out.println("请输入检索词:");
try {
in = Integer.toHexString(System.in.read());//将控制台输入的字符转化为16进制
} catch (IOException e1) {
e1.printStackTrace();
}
while(flag){
try {
RandomAccessFile raf = new RandomAccessFile(BookName,"r");
for(int i=0;i<raf.length();i++){ //循环至文本末尾结束
txt = Integer.toHexString(raf.read()); //循环读取文本字符
if(in.equals(txt)){ //判断输入的字符与读取出来的字符的16进制码是否相等
count++;
}
}
all = raf.length();
flag = false;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/************计算百分比************/
NumberFormat bf = NumberFormat.getPercentInstance();
bf.setMinimumFractionDigits(0);
float rate = (float)count/all;
System.out.println("检索词词频:"+bf.format(rate));
}
}