⑴ 設計實現一個簡單的英文單詞自動過濾器, 自動獲取輸入文本中出現的在固定單詞列表WL0={I, you, he, she,
importjava.io.BufferedReader;
importjava.io.FileReader;
publicclassStatWord{
publicstaticvoidmain(String[]args){
try{
Stringfile=".txt";
String[]keywords=newString[]{"I","you","he","she","it","we","they"};
int[]result=newStatWord().stat(file,keywords);
for(inti=0;i<keywords.length;i++){
System.out.println(keywords[i]+":"+result[i]);
}
}catch(Exceptione){
e.printStackTrace();
}
}
privateint[]stat(StringfilePath,String[]keywords)throwsException{
if(keywords==null){
returnnull;
}
Stringcontent=readFile(filePath);
if(content==null){
returnnull;
}
int[]result=newint[keywords.length];
for(inti=0;i<keywords.length;i++){
result[i]=stat(content,keywords[i]);
}
returnresult;
}
privateStringreadFile(Stringtxt)throwsException{
BufferedReaderbr=newBufferedReader(newFileReader(txt));
StringBuildersb=newStringBuilder();
while(true){
Stringline=br.readLine();
if(line==null){
break;
}
sb.append(line).append(' ');
}
if(sb.length()>0){//deletethelast' '
sb.setLength(sb.length()-1);
}
br.close();
returnsb.toString();
}
privateintstat(Stringcontent,Stringkeyword){
intcount=0;
intstart=-keyword.length();
while(true){
start=content.indexOf(keyword,start+keyword.length());
if(start<0){
break;
}
if((start-1>=0&&Character.isLetter(content.charAt(start-1)))
||(start+keyword.length()<content.length()&&Character.isLetter(content.charAt(start+keyword.length())))
){//maybelike:find"he",butthewordis"she"、"together"...
continue;
}
count++;
}
returncount;
}
}