選用的英文文本為飄;
package myproject1;
//先導入飄的文本
//讀取飄的文本
//並通過分隔符統計每個單詞出現的次數,和計算單詞總數
//輸出出現次數最多的單詞和其出現次數
import java.io.;
import java.util.;
public class piao {
public static void main(String[] args) throws FileNotFoundException
{
File file=new File("D:\english\piaow.txt");
if(!file.exists())
{
System.out.println("文件不存在");
return;
}
Scanner scanner=new Scanner(file);
//單詞和數量映射表
HashMap<String, Integer > hashMap=new HashMap<String,Integer>();
System.out.println("文章-----------------------------------");
while(scanner.hasNextLine())
{
String line=scanner.nextLine();
System.out.println(line);
//\w+ : 匹配所有的單詞
//\W+ : 匹配所有非單詞
String[] lineWords=line.split("\W+");//用非單詞符來做分割,分割出來的就是一個個單詞
Set<String> wordSet=hashMap.keySet();
for(int i=0;i<lineWords.length;i++)
{
//如果已經有這個單詞了,
if(wordSet.contains(lineWords[i]))
{
Integer number=hashMap.get(lineWords[i]);
number++;
hashMap.put(lineWords[i], number);
}
else
{
hashMap.put(lineWords[i], 1);
}
}
}
System.out.println("統計單詞:------------------------------");
Iterator<String> iterator=hashMap.keySet().iterator();
while(iterator.hasNext())
{
String word=iterator.next();
// System.out.printf("單詞: "+word+"出現次數:"+hashMap.get(word));
System.out.printf("單詞:%-12s 出現次數:%d\n",word,hashMap.get(word));
}
}
}
