最近学习java字符串部分,用正则表达式做了一个简单的统计单词出现次数的小程序,目前只能统计英文。
整个程序包括三个包,分别为output,run,wordcount
wordCount包
执行单词统计逻辑的工具包,使用HashMap存储某个字符串出现的次数。
setPattern用来在类外部设置不同的正则表达式,从而使用不同的分词规则(策略模式的一个变种吧),默认使用[a-zA-Z]+
getMap返回存储统计结果的map,map用来给输出器(outputProcesser)将结果输出到控制台或文件。
源代码:
 
package wordCount;
 
import java.util.*;
import java.util.Map.*;
import java.util.regex.*;
 
public class WordCount{
private String pattern = new String("([a-zA-Z]+)");
private HashMap map;
 
public void setPatterm(String p){
this.pattern = p;
}
 
public Map getMap(){
return this.map;
}
 
public void count(String str){
this.map = new HashMap();
Matcher matcher = Pattern.compile(this.pattern).matcher(str);
 
String key;
while ( matcher.find() ){
key = matcher.group();
if ( this.map.containsKey(key) ){
this.map.put(key, this.map.get(key) + 1);
}else {
this.map.put(key, 1);
}
}
}
}
 
output包
这个包包括了三个类,OutputProcesser,ConsoleOutput,FileOutput,其中OutputProcesser作为基类
 
OutputProcesser.java
构造器接收一个来自wordCount返回的map
processInternal()申明为抽象方法,不同的子类实现不同输出方式
output()作为外部调用的接口,接口会循环map,给processInternal提供entry,processInternal会根据提供的entry进行自己的输出
beforeOutput()在输出循环开始前调用
afterOutput()在输出循环结束后调用,这两个方法使用了模板设计模式,用于子类进行输出准备和结束操作,如输出到文件时,在循环开始前打开文件,循环结束之后关闭文件
package output;
 
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
public abstract class OutputProcesser {
private Map map;
 
public OutputProcesser(Map map){
this.map = map;
}
 
public void output(){
if ( this.beforeOutput(this.map) ){
Iterator> iterator = this.map.entrySet().iterator();
 
while ( iterator.hasNext() ){
this.processInternal(iterator.next());
}
this.afterOutput(this.map);
}
}
 
protected boolean beforeOutput(Map map){
return true;
}
 
protected void afterOutput(Map map){
}
 
abstract protected void processInternal(Entry entry);
}
 
ConsoleOutput.java
package output;
 
import java.util.Map.Entry;
import java.util.*;
 
public class ConsoleOutput extends OutputProcesser{
public ConsoleOutput(Map map) {
super(map);
}
 
protected void processInternal(Entry entry){
System.out.println(this.logString(entry));
}
 
protected String logString(Entry entry){
return entry.getKey()+" : "+entry.getValue()+" times";
}
}
 
FileOutput.java
package output;
 
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
 
public class FileOutput extends ConsoleOutput{
private String filePath = "result.txt";
private FileWriter fw;
private PrintWriter pw;
public FileOutput(Map map) {
super(map);
}
protected boolean beforeOutput(Map map){
try {
this.fw = new FileWriter(this.filePath);
this.pw = new PrintWriter(this.fw);
} catch (IOException e) {
System.out.println("IOException before process output");
}
return true;
}
protected void afterOutput(Map map){
try {
this.pw.close();
this.fw.close();
} catch (IOException e) {
System.out.println("IOException after process output");
}
}
 
protected void processInternal(Entry entry){
this.pw.println(this.logString(entry));
}
}
 
run包
该包对wordCount进行测试,并调用输出类,同时进行简单的性能测试(使用内存和耗时)。
首先会打开一个文本,并读入内存,将文本交给wordCount进行处理
package run;
 
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.ConsoleHandler;
import org.omg.SendingContext.RunTime;
 
import wordCount.WordCount;
import output.*;
 
public class Run {
private long totalMemory = 0,time1 = 0,time2 = 0,memoryUsage = 0;
public void beginProfile(){
this.totalMemory = Runtime.getRuntime().totalMemory();
this.time1 = this.time2 = System.currentTimeMillis();
}
public void endProfile(){
this.memoryUsage = this.totalMemory - Runtime.getRuntime().freeMemory();
this.time2 = System.currentTimeMillis();
System.out.println("memory usage:"+this.memoryUsage+" B");
System.out.println("time usage:"+(this.time2 - this.time1)+"ms");
}
public String readFromFile(String filePath){
File file = new File(filePath);
Long fLength = file.length();
byte[] content = new byte[fLength.intValue()];
try {
FileInputStream input = new FileInputStream(file);
input.read(content);
input.close();
} catch (Exception e) {
}
 
return new String(content);
}
public static void main(String[] args) {
Run run = new Run();
WordCount wordCount = new WordCount();
run.beginProfile();
wordCount.count(run.readFromFile("messages.txt"));
run.endProfile();
OutputProcesser out = new FileOutput(wordCount.getMap());
out.output();
}
 
}
 
下面是简单的性能测试结果

java根据标点英文分词的更多相关文章

  1. python 安装nltk,使用(英文分词处理,词干化等)(Green VPN)

    安装pip命令之后: sudo pip install -U pyyaml nltk import nltk nltk.download() 等待ing 目前访问不了,故使用Green VPN htt ...

  2. 英文分词算法(Porter stemmer)

    http://blog.csdn.net/whuslei/article/details/7398443 最近需要对英文进行分词处理,希望能够实现还原英文单词原型,比如 boys 变为 boy 等. ...

  3. Atitit.java expression fsm 表达式分词fsm引擎

    Atitit.java expression fsm 表达式分词fsm引擎 C:\0workspace\AtiPlatf_cms\src\com\attilax\fsm\JavaExpFsm.java ...

  4. Apache Solr 初级教程(介绍、安装部署、Java接口、中文分词)

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  5. ZH奶酪:Java调用NLPIR汉语分词系统

    NLPIR工具 支持自定义词表: 可以离线使用: 下载地址:http://ictclas.nlpir.org/newsdownloads?DocId=389 在线演示:http://ictclas.n ...

  6. java开发-技能要求-分词频度统计

    描述: 一哥们离职找工作,最近聊了聊面试待遇要求一类的事情,有些感触. 在一个公司呆的时间长了,对市场上对开发的要求已经不那么敏感了,也不知道人家要求哪些技能.一个公司的业务是有限的,呆了2年,3年, ...

  7. Java实验--关于英文短语词语接龙

    在课堂上经过实验之后,重新在宿舍里面从0开始编写大概30分钟左右能够完成这个实验,不是原来的思路. 该实验的表述为:从两个文本input1.txt和input2.txt中读取英文单词,若前面的英文单词 ...

  8. 综合应用,jieba,去标点,分词保存,统计,删词,输出

    import jieba fp1=r'D:/python/a.txt' outph=r'D:/python/out.txt' f=open(fp1,'r',encoding='utf-8') txt= ...

  9. [Java]使用正则表达式实现分词

    手工分词稍嫌麻烦,不好维护,而利用正则表达式就利索多了.Java提供了java.util.regex.Matcher,java.util.regex.Pattern类来帮助我们实现此功能. 例一:以下 ...

随机推荐

  1. ASP.NET MVC中viewData、viewBag和templateData的区别

    在MVC3开始,视图数据可以通过ViewBag属性访问,在MVC2中则是使用ViewData.MVC3中保留了ViewData的使用.ViewBag是动态类型(dynamic),ViewData是一个 ...

  2. NetBean常用快捷键(MAC中)

    shift+cmd+i:导入包 shift+alt+上:复制当前行,鼠标留在上一行   shift+alt+下:复制当前行,鼠标留在下一行 shift+ctrl+上:将选中行向上移动    shift ...

  3. python之SQLAlchemy

    ORM介绍 orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为 ...

  4. 关于mysql登录异常处理方法 - mysql ERROR 1045 (28000)

    今天在开发过程中遇到了一个很令人头痛的问题?? 使用 百度经验的步骤 [http://jingyan.baidu.com/article/495ba841ef412d38b30edeb2.html]修 ...

  5. Java Web应用包括些啥?

    Tomcat服务器最重要的作用就是充当Java Web应用的容器.Java Servlet规范中对Java Web应用的定义如下: Java Web应用由一组Servlet.HTML页面.类以及其他可 ...

  6. 30.Nginx集群搭建笔记

    源码安装Nginx: tar -zxvf nginx-1.8.0.tar.gz -C /nginx/        #解压Nginx rpm -ivh keepalived-1.2.13-5.el6_ ...

  7. 测试oracle数据库的脱机备份和恢复

    环境:windows7.Oracle11g 一.脱机备份 脱机备份是指在数据库关闭情况下的数据备份,也称为冷备份. 在书上学到的备份步骤: 1.记录所要备份数据库文件所在的操作系统路径: 2.关闭数据 ...

  8. matlab播放音乐

    最近在做计算,写了一些matlab代码,脑壳还疼,所以决定发挥一下逗B精神,写一个程序玩一下. 想了想,既然写代码的时候喜欢听歌,而且我的电脑打开网易音乐的速度巨慢(不知道为什么..),那些一个程序直 ...

  9. 【BZOJ】3436: 小K的农场

    3436: 小K的农场 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 938  Solved: 417[Submit][Status][Discuss ...

  10. djangocms安装技巧

    首先python的版本要高一些,否则安装django-cms会报错 安装cmsinstaller不能够正常下载 利用virtualenv进行安装配置 注意中文的配置 djangocms配置中文 dja ...