Java 统计文本文件中字符数量

设有一个文本文件word01.txt,内容如下:

after a minute or two and said to his friend he opened them again
a minute or two and said to
friend he opened them again
and closed and to his

编写程序,统计文件中每个字母出现的次数。
输出示例如下

{ =27, a=13, c=1, d=11, e=14, f=3, g=2, h=6, i=10, l=1, m=4, n=12, o=10, p=2, r=5, s=5, t=10, u=2, w=2}

这个题目原本是java大数据的一道经典例题——统计单词数,今天装好开发环境后想写一个程序试试手,就选了这个题目,审题不仔细,写完才发现写错了。但也将错就错了,毕竟两个代码差异不算太大。

读取文件

这个例题的核心点就两个,一个是读取文本文件,一个是统计。读取文本文文件就不详解了,直接从网上找的。代码如下:

class FileTools {
    /*
     * 调用时传递文本文件的路径
     * 读取文本内容,按行读取,返回文本字符串
     * */
    public String readFile(String pathname) {
        File file = new File(pathname);
        String text = "";
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(pathname);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
//                text = text + str + "\n";     //保留换行
                text = text + str;              //不保留换行
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;

    }
}

HashMap

HashMap存储的内容是键值对(key-value)映射,在进行数据存储时可以标记成 字符:数量 的形式。在本例子中HashMap的使用方式如下:

Map<String, Integer> map = new HashMap<String, Integer>();

别问为什么不用 int,HashMap 中的元素实际上是对象,一些常见的基本类型要使用它的包装类。
附上其对照表:

基本类型引用类型
booleanBoolean
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter

在写其他项目时按需要选择即可。
在添加元素时,HashMap会保证key的唯一性,不会重复添加key,所以在统计时,可以先使用get方法取出要累加字符的当前数量,+1后重新put就可以。当然,如果HashMap中还没有的元素,get会得到一个null。所以,还要提前写一个if,如果得到的是null,重新赋值为0.
这一部分的代码单独拿出来让各位注意下:

	count = map.get(String.valueOf(text.charAt(i)));	//String.valueOf将char转为字符转
	if (count == null)
	   count = 0;
	count++;
	map.put(String.valueOf(text.charAt(i)), count);

然后就不多废话,全部代码如下

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class test {


    public static void main(String[] args) {
        String pathname = "files/word01.txt";
        String text = "";
        Integer count = 0;				//与HashMap的Integer对应
        FileTools file_tools = new FileTools();       //调用类,读取文本
        text = file_tools.readFile(pathname);
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < text.length(); i++) {
            count = map.get(String.valueOf(text.charAt(i)));
            if (count == null)
                count = 0;
            count++;
            map.put(String.valueOf(text.charAt(i)), count);
        }
        System.out.println(map);
        
    }
}

class FileTools {
    /*
     * 调用时传递文本文件的路径
     * 读取文本内容,按行读取,返回文本字符串
     * */
    public String readFile(String pathname) {
        File file = new File(pathname);
        String text = "";
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(pathname);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
//                text = text + str + "\n";     //保留换行
                text = text + str;              //不保留换行
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;

    }
}

如有错误,欢迎指正。

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要解析一个文本文件统计相同类型的数据数量,可以使用Java的文件读取字符串处理功能。以下是一个基本的实现: 1. 首先,使用Java的文件读取功能读取文本文件并将其存储到一个字符。 2. 然后,使用Java字符串分割功能将字符串分割成一行一行的数据。 3. 对于每一行数据,使用Java的正则表达式或其他字符串处理功能识别出数据类型,并将其加入一个HashMap。 4. 最后,遍历HashMap并输出每种数据类型及其数量。 以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class TextParser { public static void main(String[] args) { String fileName = "example.txt"; // 读取文件并将其存储到字符 String fileContent = ""; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { fileContent += line + "\n"; } } catch (IOException e) { e.printStackTrace(); } // 分割字符串成一行一行的数据 String[] lines = fileContent.split("\n"); // 统计数据类型数量 Map<String, Integer> typeCount = new HashMap<>(); for (String line : lines) { // 识别数据类型 String type = ""; if (line.matches("\\d+")) { type = "number"; } else if (line.matches("[A-Za-z]+")) { type = "string"; } else { type = "other"; } // 将数据类型加入HashMap并增加数量 if (typeCount.containsKey(type)) { typeCount.put(type, typeCount.get(type) + 1); } else { typeCount.put(type, 1); } } // 输出结果 for (Map.Entry<String, Integer> entry : typeCount.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ``` 请注意,这只是一个简单的示例代码,可能需要根据实际情况进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值