Java: 使用HashMap统计文件中单词个数

本文介绍了一种使用Java进行文本处理的方法,通过去除除单引号外的所有英文标点,并统计单词出现频率。该方法利用HashMap来记录每个单词出现的次数,适用于简单的文本分析任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:将除单引号的英文标点换成空格,然后逐词解决计数问题。

直接上代码:

// Coding starts here

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主类。
 * @author Hippo
 *
 */
public class Main
{
    private static char[] punctuations = new char[] {',', '.', '/', '\\', '?', '!', '@', '#', '$', '%',
            '&', '*', '(', ')', '|', ':', ';', '-', '=', '+', '[', ']', '{', '}', '_', '\"'};
    
    public static void main(String[] strings) throws IOException
    {
        List<String> all = Files.readAllLines(Paths.get("D:\\hippo.txt"));
        Map<String, Integer> map = new HashMap<>();
        String checked;
        for(String current : all)
        {
            checked = check(current);
            String[] words = checked.split(" ");
            for(String word : words)
            {
                word = word.trim().toLowerCase();
                if(word.equals(" "))
                    continue;
                if(!map.containsKey(word))
                    map.put(word, 1);
                else
                {
                    int times = map.get(word) + 1;
                    map.remove(word);
                    map.put(word, times);
                }
            }
        }
        
        System.out.println(map);
    }
    
    /**
     * 优化字符串,将除单引号外的英文标点符号替换成空格。
     * @param s 待优化的字符串
     * @return 优化后的结果
     */
    public static String check(String s)
    {
        for(int i = 0; i < s.length(); i++)
            if(isPunctuation(s.charAt(i)))
                s = s.replace(s.charAt(i), ' ');
        return s;
    }
    
    public static boolean isPunctuation(char c)
    {
        for(char each : punctuations)
            if(c == each)
                return true;
        return false;
    }
}

分析文章:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!


分析结果:

{explain=2, silently=1, peters=1, preferably=1, bad=1, counts=1, simple=1, rules=1, do=2, nested=1, good=1, dutch=1, beautiful=1, that=1, ambiguity=1, complex=2, than=8, should=2, only=1, tim=1, if=2, those=1, zen=1, python=1, pass=1, in=1, it's=1, let's=1, ugly=1, often=1, is=10, it=2, easy=1, dense=1, explicit=1, never=3, practicality=1, at=1, sparse=1, temptation=1, guess=1, aren't=1, errors=1, namespaces=1, silenced=1, implicit=1, explicitly=1, be=3, purity=1, idea=3, not=1, refuse=1, unless=2, are=1, flat=1, and=1, by=1, you're=1, now=2, of=3, hard=1, a=2, cases=1, may=2, break=1, more=1, implementation=2, one=3, beats=1, enough=1, right=1, honking=1, great=1, way=2, special=2, better=8, the=6, readability=1, face=1, although=3, complicated=1, there=1, obvious=2, to=5, first=1}


在进阶的路上,欢迎各位大神指正。

可以使用Java文件读取和字符串处理功能来实现统计文件单词个数的功能。具体实现步骤如下: 1. 首先需要读取文件中的所有内容。可以使用Java的File和Scanner类来实现。具体代码如下: ```java File file = new File("文件路径"); Scanner scanner = new Scanner(file); String content = ""; while (scanner.hasNextLine()) { content += scanner.nextLine(); } scanner.close(); ``` 2. 将读取到的内容按照空格进行分割,得到所有单词。可以使用Java的split方法来实现。具体代码如下: ```java String[] words = content.split("\\s+"); ``` 3. 统计单词个数。可以使用JavaHashMap来实现。具体代码如下: ```java Map<String, Integer> wordCountMap = new HashMap<>(); for (String word : words) { if (wordCountMap.containsKey(word)) { wordCountMap.put(word, wordCountMap.get(word) + 1); } else { wordCountMap.put(word, 1); } } ``` 4. 输出结果。可以使用Java的System.out.println方法来输出结果。具体代码如下: ```java for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } ``` 完整代码如下: ```java import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class WordCount { public static void main(String[] args) { File file = new File("文件路径"); Scanner scanner = null; try { scanner = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } String content = ""; while (scanner.hasNextLine()) { content += scanner.nextLine(); } scanner.close(); String[] words = content.split("\\s+"); Map<String, Integer> wordCountMap = new HashMap<>(); for (String word : words) { if (wordCountMap.containsKey(word)) { wordCountMap.put(word, wordCountMap.get(word) + 1); } else { wordCountMap.put(word, 1); } } for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值