本周根据杨老师的spec对英语文章词频统计进行了改进
1.需求分析:
对英文文章中的英文单词进行词频统计并按照有大到小的顺序输出,
2.算法思想:
(1)构建一个类用于存放英文单词及其出现的次数
class WordAndNum{
public String word;
public int num;
}
(2)从txt中获取字符串
BufferedReader in=new BufferedReader(new FileReader("D:\\test.txt"));
String line=null;
while((line=in.readLine())!=null)
(3)将字符串中的单词截取出来存到ArrayList中
ArrayList<WordAndNum> list=new ArrayList<WordAndNum>();
int index1=0;
int index2 = 0;
//截取英文单词
index1=line.indexOf(" ");
String word=line.substring(0,index1);
WordAndNum wdn=new WordAndNum();
wdn.word=word;
wdn.num=1;
list.add(wdn);
for(int i=index1+1;i<line.length();i++){
if(line.charAt(i)==','||line.charAt(i)=='.'||line.charAt(i)==';'||line.charAt(i)==' '||line.charAt(i)=='?'){
index2=i;
WordAndNum wdn2=new WordAndNum();
word=line.substring(index1+1,index2);
wdn2.word=word;
boolean flag=falsefor(int j=0;j<list.size();j++){
if(list.get(j).word.equals(word)){
wdn2.num=list.get(j).num+1;
list.set(j, wdn2);
flag=true;
break;
}
}
if(flag==false){
wdn2.num=1;
list.add(wdn2);
}
index1=index2;
}
}
(4)对ArrayList进行冒泡排序
//冒泡排序
for(int i=0;i<list.size();i++){
for(int j=0;j<list.size()-i-1;j++){
if(list.get(j).num<list.get(j+1).num){
WordAndNum wd1=list.get(j);
WordAndNum wd2=list.get(j+1);
list.set(j, wd2);
list.set(j+1, wd1);
}
}
}
3.具体代码
package ruan.jian.gong.cheng; import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList; class WordAndNum{
public String word;
public int num;
} public class wordNum2 {
public static void main(String[] args) {
try{
BufferedReader in=new BufferedReader(new FileReader("D:\\test.txt"));
String line=null;
ArrayList<WordAndNum> list=new ArrayList<WordAndNum>();
while((line=in.readLine())!=null){
int index1=0;
int index2 = 0;
//截取英文单词
index1=line.indexOf(" ");
String word=line.substring(0,index1);
WordAndNum wdn=new WordAndNum();
wdn.word=word;
wdn.num=1;
list.add(wdn);
for(int i=index1+1;i<line.length();i++){
if(line.charAt(i)==','||line.charAt(i)=='.'||line.charAt(i)==';'||line.charAt(i)==' '||line.charAt(i)=='?'){
index2=i;
WordAndNum wdn2=new WordAndNum();
word=line.substring(index1+1,index2);
wdn2.word=word;
boolean flag=false;
for(int j=0;j<list.size();j++){
if(list.get(j).word.equals(word)){
wdn2.num=list.get(j).num+1;
list.set(j, wdn2);
flag=true;
break;
}
}
if(flag==false){
wdn2.num=1;
list.add(wdn2);
}
index1=index2;
}
}
}
//冒泡排序
for(int i=0;i<list.size();i++){
for(int j=0;j<list.size()-i-1;j++){
if(list.get(j).num<list.get(j+1).num){
WordAndNum wd1=list.get(j);
WordAndNum wd2=list.get(j+1);
list.set(j, wd2);
list.set(j+1, wd1);
}
}
}
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).word+"==="+list.get(i).num);
}
}catch(Exception e){
e.printStackTrace();
} }
}
4.以如下英文文章为例,输出结果为
5.结果分析:可以对英文文章进行词频统计并按从大到小进行输出