本文要解决的问题:“键盘输入一段英语语句,将这段话写入content.txt中,然后输出这段话,并且统计语句中英文单词的数目以及各个单词出现的次数。”

分析问题知,核心是文件读写和单词统计。

单词统计可以参考我以前的一篇文章:java源码——统计字符串中字符出现的次数,不过要注意的是以前这篇文章是统计字符,不用判断是否是单词,本问题中统计单词就要判断多少字符是一个单词,同时忽略大小写问题。

文件读写不是很难,方法基本是死的,不用考虑方法。代码解决问题的难点还是单词的统计,我的代码中用了正则表达式匹配:"[a-zA-Z]+",这个能匹配所有英文单词。

下面上代码。

Filereadwrite.java

/**
* <p>Title: Filereadwrite.java</p>
* <p>Description: </p>
*
* @author fuxuemingzhu
*
* @email fuxuemingzhu@163.com
*
* @date 2014年12月5日 下午4:05:40
* @version 1.0
*/
package com.fuxuemingzhu.filereadwrite.main; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* <p>
* Title: FileReadWrite
* </p>
* <p>
* Description:由键盘输入文字,保存到相应目录下的txt中。由txt中读取内容并且进行单词统计
* </p>
*
* @author fuxuemingzhu
*
* @email fuxuemingzhu@163.com
*
* @date 2014年12月5日 下午4:05:40
*/
public class FileReadWrite { /**
* inputString 键盘输入的字符串
*/
public static String inputString = new String(); /**
* filePath 文件存储路径
*/
public static String filePath = new String("E:/学习/java/content.txt"); /**
* fileContent 文件内容
*
*/
public static String fileContent = new String(); /**
* wordsCount 存放单词和其对应数目的HashMap
*/
public static HashMap<String, Integer> wordsCount = new HashMap<String, Integer>(); /**
* <p>
* Title: main
* </p>
* <p>
* Description:main方法,程序的入口
* </p>
*
* @param args
*
*/
public static void main(String[] args) {
input();
try {
writeFile(inputString, filePath);
fileContent = readFile(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
output(fileContent);
} /**
* <p>
* Title: input
* </p>
* <p>
* Description:由键盘输入文字
* </p>
*
*/
public static void input() {
System.out.println("请输入要保存到txt中的内容:");
Scanner scanner = new Scanner(System.in);
inputString = scanner.nextLine();
scanner.close();
System.out.println("文本扫描成功!");
} /**
* <p>
* Title: output
* </p>
* <p>
* Description:读取txt,并且统计输出单词和其对应数目
* </p>
*
* @param outputString
*
*/
public static void output(String outputString) {
System.out.println("您输入的文本由txt中读取出来咯,内容是:");
System.out.println(outputString);
countWords();
System.out.println("输入的文本中共有" + wordsCount.size() + "个英语单词。");
System.out.println("统计分析如下(已忽略大小写):");
for (Iterator<String> iterator = wordsCount.keySet().iterator(); iterator
.hasNext();) {
String words = (String) iterator.next();
int num1 = wordsCount.get(words);
System.out.println("\"" + words + "\"出现了" + num1 + "次");
}
} /**
* <p>
* Title: countWords
* </p>
* <p>
* Description:用HashMap保存每个单词出现的次数
* </p>
*
*/
public static void countWords() {
Pattern expression = Pattern.compile("[a-zA-Z]+");// 定义正则表达式匹配单词
String string1 = fileContent.toLowerCase();// 转换成小写
Matcher matcher = expression.matcher(string1);
String word = null;// 文章中的单词
while (matcher.find()) {// 是否匹配单词
word = matcher.group();// 得到一个单词-树映射的键
if (wordsCount.containsKey(word)) {
wordsCount.put(word, wordsCount.get(word) + 1);
} else {
wordsCount.put(word, 1);
}
}
} /**
* <p>
* Title: writeFile
* </p>
* <p>
* Description:写入文件
* </p>
*
* @param str
* 要保存的内容
* @param savePath
* 保存的文件路径
* @throws Exception
* 找不到路径
*
*/
public static void writeFile(String str, String savePath) throws Exception {
System.out.println("txt保存路径是:" + savePath);
BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
System.out.println("txt创建成功!");
bw.write(str);
System.out.println("文本内容存储到txt中成功!");
bw.close(); } /**
* <p>
* Title: readFile
* </p>
* <p>
* Description:读取文件
* </p>
*
* @param file
* @return 文件内容
* @throws Exception
*
*/
public static String readFile(File file) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(file));
System.out.println("打开文件成功!");
StringBuffer sbf = new StringBuffer("");
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line).append("\r\n");// 按行读取,追加换行\r\n
}
System.out.println("文件内容读取成功!");
br.close();
return sbf.toString();
}
}

附上运行效果图。

另外附上在指定位置生成的content.txt文件夹的截图。

content.txt打开效果,说明已经把键盘输入的内容写入到指定的txt文件中,并且单词统计时能够匹配到所有英语单词,非英文单词没有进行匹配。

最新文章

  1. [NOIP2008] 提高组 洛谷P1155 双栈排序
  2. Leetcode: Max Sum of Rectangle No Larger Than K
  3. 图形处理的api
  4. [Hibernate] - one to many
  5. FindBugs插件
  6. restful_api
  7. Linuxc - Makefile完成项目的管理。
  8. 我的第一个.NET Core App Windows系统
  9. [Swift]LeetCode448. 找到所有数组中消失的数字 | Find All Numbers Disappeared in an Array
  10. js基础 -函数
  11. Cetos 中添加bbr服务
  12. SuppressLint错误
  13. 使用Log4j2实现日志输出
  14. restfull环境搭建-helloword(二)
  15. SVM学习笔记2-拉格朗日对偶
  16. YOLO V3论文理解
  17. [Domino]从嵌入另一个数据库嵌入的Embedded View无法正常显示,提示unable to lauch
  18. ssh自动分发密匙脚本样板
  19. Spring Boot 入门之持久层篇(三)
  20. IBM-ETP 实训项目前一天

热门文章

  1. Augustus指南(Trainning部分)
  2. word2010在左侧显示目录结构
  3. Hive-insert into table 与 insert overwrite table 区别
  4. 使用 JDBC 驱动程序
  5. Spark(十七)【SparkStreaming需求练习】
  6. Maven打包及场景
  7. oracle加密encrypt,解密decrypt
  8. java代码定时备份mysql数据库及注意事项——基于 springboot
  9. js调用高德地图API获取地理信息进行定位
  10. Tableau预测指示器的运用