要在Java中分析文本的高频次数据,你可以使用HashMap来记录每个单词的出现次数

要在Java中分析文本的高频次数据,你可以使用HashMap来记录每个单词的出现次数。以下是一个简单的示例代码,演示如何读取文本文件,统计每个单词的频率,并输出出现次数最多的单词。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author weimeilayer@gmail.com ✨
 * @date 💓💕 2024年10月17日 🐬🐇 💓💕
 */
public class WordFrequencyAnalyzer {
    public static void main(String[] args) {
        String filePath = "d://textfile.txt"; // 替换为你的文本文件路径
        Map<String, Integer> wordCountMap = new HashMap<>();

        // 读取文本文件并统计单词频率
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 使用正则表达式分割单词,并将其转换为小写
                String[] words = line.toLowerCase().split("\\W+");
                for (String word : words) {
                    if (!word.isEmpty()) {
                        wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 排序并输出高频次单词
        int topN = 10; // 设置要输出的高频单词数量
        List<Map.Entry<String, Integer>> sortedEntries = wordCountMap.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(topN)
                .collect(Collectors.toList());

        System.out.println("Top " + topN + " Word Frequencies:");
        sortedEntries.forEach(entry -> {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        });
    }
}


输出所有

 // 输出高频次单词
        System.out.println("Word Frequencies:");
        wordCountMap.forEach((word, count) -> {
            System.out.println(word + ": " + count);
        });

python 案例

from collections import Counter
import re

def analyze_word_frequency(file_path, top_n=10):
    # 读取文本文件并统计单词频率
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read().lower()  # 将文本转换为小写
        # 使用正则表达式分割单词
        words = re.findall(r'\b\w+\b', text)
        
    # 统计单词频率
    word_count = Counter(words)

    # 输出高频次单词
    print(f"Top {top_n} Word Frequencies:")
    for word, count in word_count.most_common(top_n):
        print(f"{word}: {count}")

# 示例用法
file_path = 'd://textfile.txt'  # 替换为你的文本文件路径
analyze_word_frequency(file_path, top_n=10)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

❀͜͡傀儡师

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值