上周六我表姐让我实现一个功能:
统计一篇纯英文文章的所有句子数,并且计算每个句子的每个单词出现的频率。
基于程序员的我,第一时间想到的是这个网上应该有代码借鉴,找了半天也没找到同样的。
好我自己写。
想了一下实现逻辑也不复杂,用IO从文件中读取所有的行数,每行根据”.“分割句子,这样就能得到所有的句子,然后每个句子用hashMap循环统计单词就行。
后来发现正则也涉及了,也要注意字符串去除收尾空格,否则会出现空行等问题。
果然,大家code的时候要注意细节呀。
放上我的Java代码
public class FileReadWrite {
/**
* inputString 键盘输入的字符串
*/
public static String inputString = new String();
/**
* filePath 文件存储路径
*/
public static String filePath = new String("/Users/xiaomao/IDEA_Code/myStudyCode/englishCount/biergaici.txt");
/**
* filePath 文件存储路径
*/
public static String savePath = new String("/Users/xiaomao/IDEA_Code/myStudyCode/englishCount/save.txt");
/**
* fileContent 文件内容
*/
public static String fileContent = new String();
/**
* 读取的文件的某行
*/
public static List<String> fileLines = new ArrayList<>();
/**
* 句子合集
*/
public static List<String> sentences = new ArrayList<>();
/**
* wordsCount 存放单词和其对应数目的HashMap
*/
public static HashMap<String, Integer> wordsCount = new HashMap<String, Integer>();
/**
* 句子数量
*/
public static int count = 0;
/**
* 输出句子
*/
public static StringBuilder outString = new StringBuilder();
/**
* <p>
* Title: main
* </p>
* <p>
* Description:main方法,程序的入口
* </p>
*
* @param args
*/
public static void main(String[] args) throws Exception {
//input();
try {
//writeFile(inputString, filePath);
fileContent = readFile(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
//获取所有的句子
fileLines.stream().filter(Objects::nonNull).filter(one -> !one.isEmpty()).forEach(
one -> {
String[] split = one.split("\.");
Arrays.stream(split).forEach(oneSentence -> {
oneSentence = oneSentence.trim();
if (oneSentence.isEmpty()) {
return;
}
sentences.add(oneSentence);
});
}
);
count = sentences.size();
outString.append("总句子数:").append(count).append("\n");
outString.append("\n");
sentences.forEach(FileReadWrite::output);
System.out.println(outString);
writeFile();
}
/**
* <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:读取某个句子,并且统计输出单词和其对应数目
* </p>
*
* @param oneSentence
*/
public static void output(String oneSentence) {
int i = sentences.indexOf(oneSentence);
outString.append("第").append(i + 1).append("句的内容是:").append("\n");
outString.append(oneSentence).append(".").append("\n");
countWords(oneSentence);
}
/**
* <p>
* Title: countWords
* </p>
* <p>
* Description:用HashMap保存每个单词出现的次数
* </p>
*/
public static void countWords(String oneSentence) {
// 定义正则表达式匹配单词
HashMap<String, Integer> wordsCount = new HashMap<>(20);
Pattern expression = Pattern.compile("[a-zA-Z]+");
// 转换成小写
String string1 = oneSentence.toLowerCase();
Matcher matcher = expression.matcher(string1);
// 文章中的单词
String word;
// 是否匹配单词
while (matcher.find()) {
// 得到一个单词-树映射的键
word = matcher.group();
if (wordsCount.containsKey(word)) {
wordsCount.put(word, wordsCount.get(word) + 1);
} else {
wordsCount.put(word, 1);
}
}
outString.append("本句中共有").append(wordsCount.size()).append("个英语单词。").append("\n");
outString.append("统计分析如下(已忽略大小写):").append("\n");
wordsCount.forEach((key, value) -> {
outString.append(""").append(key).append(""出现了").append(value).append("次").append("\n");
});
outString.append("\n");
}
/**
* <p>
* Title: writeFile
* </p>
* <p>
* Description:写入文件
* </p>
*
* @throws Exception 找不到路径
*/
public static void writeFile() throws Exception {
System.out.println("txt保存路径是:" + savePath);
//1. 使用FileOutputStream写
File file = new File(savePath);
//如果文件不存在,创建文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write(outString.toString().getBytes(StandardCharsets.UTF_8));
fos.close();
System.out.println("文本内容存储到txt中成功!");
//2. 使用BufferWriter写
// BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
// System.out.println("txt创建成功!");
// bw.write(String.valueOf(outString));
// 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("打开文件成功!");
StringBuilder sbf = new StringBuilder("");
String line = null;
while ((line = br.readLine()) != null) {
// 按行读取,追加换行\r\n
fileLines.add(line);
sbf.append(line).append("\r\n");
}
System.out.println("文件内容读取成功!");
br.close();
return sbf.toString();
}
}
我觉得优化的地方还是有很多的,大佬们多多指点呀!