import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set; public class 统计单词
{
public static void main(String[] args) throws FileNotFoundException
{
File file=new File("C:\\Users\\hp\\eclipse-workspace\\English.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));
} System.out.println("程序结束--------------------------------");
}
}

  运行结果:

文章-----------------------------------
a a a a aa aa aaa aaa aaaa aaaa
统计单词:------------------------------
单词: 出现次数:1
单词:aa 出现次数:2
单词:aaa 出现次数:2
单词:a 出现次数:4
单词:aaaa 出现次数:2
程序结束--------------------------------

  

WordConuts的更多相关文章

随机推荐

  1. 20170803 Airflow自带的API进行GET 和POST动作部分内容

    --1 首先你要有安装好的Airflow 环境并且在配置文件中有启用API 属性 --2 就是GET 和POST 方法的调用了 这里说一下,由于Airflow在网络上的资料比较少,可以从GETHUB中 ...

  2. MySQL大表DROP删除小技巧(转)

    在日常工作中,经常会遇到历史大表从主库上迁移到备份机,以便腾出主库空间,那么如果你直接drop table 后,可能会引起数据库抖动,连接数升高等问题,从而影响业务. 那么用一个小技巧,即可轻松平滑的 ...

  3. 照葫芦画瓢之爬虫豆瓣top100

    import requestsimport reimport jsonfrom requests.exceptions import RequestExceptiondef get(url):    ...

  4. python基础(9)-迭代器&生成器函数&生成器进阶&推导式

    迭代器 可迭代协议和迭代器协议 可迭代协议 只要含有__iter__方法的对象都是可迭代的 迭代器协议 内部含有__next__和__iter__方法的就是迭代器 关系 1.可以被for循环的都是可迭 ...

  5. IOP知识点(2)

    1   URL资源访问不足时,需要添加URL权限 2   重定向问题解决办法:3  cloud-service-factory 项目 gradlew方法 1   URL资源访问不足时,需要添加URL权 ...

  6. css页面布局--三栏(两边固定中间自适应&两边自适应中间固定)

    http://www.cnblogs.com/zhanyishu/p/5656875.html

  7. 日期选择器和日期条控件 DateChooserAndDateFieldControls

    日期选择器和日期条控件 书:161 <?xml version="1.0" encoding="utf-8"?> <s:Application ...

  8. jquery简介未完成

    jQuery jQuery是一个快速.简洁的javascript框架,是继prototype之后又一个优秀的代码库(或者javascript框架).jQuery设计的宗旨是writeLess,Do M ...

  9. C# dataGridView 如何选中整行?

    this.dataGridView1.SelectionMode =DataGridViewSelectionMode.FullRowSelect; dataGridView1即你的dataGridV ...

  10. beego 初体验 - orm

    goland Terminal运行命令: go get github.com/astaxie/beego/orm 安装go mysql驱动: go get github.com/go-sql-driv ...