Java-词频统计

本文介绍了如何使用Java编程实现词频统计。首先在项目中创建一个包含单词的文本文件,然后通过WordCount类遍历文件内容,对每行单词进行拆分并统计词频,最后按照指定格式输出统计结果。
摘要由CSDN通过智能技术生成

编程实现

  • 在项目里创建一个单词文本文件words.txt
    在这里插入图片描述

创建WordCount 遍历文件

在这里插入图片描述
运行程序,
在这里插入图片描述

  • 拆分
    在这里插入图片描述

运行程序,
在这里插入图片描述

  • 针对每行单词数组进行词频统计
    在这里插入图片描述
    运行程序,
    在这里插入图片描述
  • 按照指定格式输出词频统计结果
public class WordCount {
   
    public static void main
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现词频统计的一种简单方法是使用Java中的HashMap数据结构,将每个单词作为键,出现次数作为值。具体实现步骤如下: 1. 读取文本文件,将文件内容存储在一个字符串中。 2. 使用正则表达式将字符串中的非字母字符替换为空格,以便将文本分割成单词。 ```java String content = readFileAsString("input.txt"); // 读取文本文件 content = content.replaceAll("[^a-zA-Z]", " "); // 将非字母字符替换为空格 ``` 3. 将文本分割成单词,并统计每个单词出现的次数。 ```java Map<String, Integer> wordCount = new HashMap<>(); String[] words = content.split("\\s+"); for (String word : words) { word = word.toLowerCase(); // 将单词转换为小写字母,以便不区分大小写 if (!word.isEmpty()) { int count = wordCount.getOrDefault(word, 0); wordCount.put(word, count + 1); } } ``` 4. 输出每个单词及其出现次数。 ```java for (String word : wordCount.keySet()) { int count = wordCount.get(word); System.out.println(word + ": " + count); } ``` 完整代码如下: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class WordCount { public static void main(String[] args) throws IOException { String content = readFileAsString("input.txt"); // 读取文本文件 content = content.replaceAll("[^a-zA-Z]", " "); // 将非字母字符替换为空格 Map<String, Integer> wordCount = new HashMap<>(); String[] words = content.split("\\s+"); for (String word : words) { word = word.toLowerCase(); // 将单词转换为小写字母,以便不区分大小写 if (!word.isEmpty()) { int count = wordCount.getOrDefault(word, 0); wordCount.put(word, count + 1); } } for (String word : wordCount.keySet()) { int count = wordCount.get(word); System.out.println(word + ": " + count); } } private static String readFileAsString(String filePath) throws IOException { return new String(Files.readAllBytes(Paths.get(filePath))); } } ``` 其中,`readFileAsString`方法用于读取文本文件并返回字符串。如果需要统计多个文件的词频,可以将整个统计过程放到一个循环中,每次读取一个文件并更新词频统计结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值