gpt4 book ai didi

java - 如何计算 HashMap 中的单词

转载 作者:行者123 更新时间:2023-12-04 18:05:56 26 4
gpt4 key购买 nike

我拼凑了这段代码,当然是在一些帮助下。它的重点是获取一条用户消息并检查文本文件以查看消息中的任何单词是否也在文本文件中找到(大约 50 个常用英语单词)。我的问题是我还想计算消息中每个单词的出现次数。我试图添加一个 int 计数器,但出现错误,因为我无法用整数计算字符串对象。如果我只是添加一个计数器到:

for (String userInput : message.split(" ")) 
{
if (legalEnglishWords.contains(userInput))
{
System.out.println(userInput + " is an English word ");
count++;
System.out.println(userInput + " occurs " + counter + " times");
}
}

我对每个通过合法单词测试的单词进行迭代,使我的输出看起来像

Please enter in a message: 
transformers are is is this

transformers occurs 0 times
are is an English word
are occurs 1 times
is is an English word
is occurs 2 times
is is an English word
is occurs 3 times
this is an English word
this occurs 4 times

如您所见,计数完全错误,我显示消息中出现的单词的次数。我只希望它显示一次。我想在上面的 if 语句中加入一个 && 来检查这个词是否已经被打印出来,但我不知道该放什么。我也不知道如何只计算 if 语句中的单个单词,而不是每次输入 if 语句时都计算。所以基本上我需要一些帮助来计算单个单词,同时只显示一次“英语”单词,以及它在最后出现的次数。我对 Java 还是有点陌生​​,并且了解我的程序中发生的所有事情以及原因。因此,如果可能的话,我想尝试只增加这段代码来做必要的事情,而不是对我可能不理解的事情进行全面检修。非常感谢大家!

import java.io.*;
import java.util.HashSet;
import java.util.Scanner;

public class Affine_English3
{
public static void main(String[] args) throws IOException
{
HashSet<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
int counter = 0;

while (file.hasNextLine())
{
String line = file.nextLine();

for (String word : line.split(" "))
{
{
legalEnglishWords.add(word);
}
}
}

file.close();

Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = scan.nextLine();
scan.close();

for (String userInput : message.split(" "))
{
if (legalEnglishWords.contains(userInput))
{
System.out.println(userInput + " is an English word ");
counter++;
}
System.out.println(userInput + " occurs " + counter + " times");
}
}
}

这是我的“常用英语单词”文本文件的副本

the he at but there  of was be not use and for can 
a on have all each to are from where which in by
is with line when do you his had your how that they
it i word said if this what an as or we she their

最佳答案

您的方向是正确的,但您需要更改存储数据的集合。如果你想对每个单词进行计数,那么在 Java 中这需要一个 Map。映射将一组键映射到一组值——类似于将姓名映射到年龄。在您的情况下,您希望将单词映射到计数。

所以从声明如下的 map 开始:

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

然后每次遇到一个词时,您可以执行以下操作:

if (!wordCounts.containsKey(word))
wordCounts.put(word, 1);
else
wordCounts.put(word, wordCounts.get(word) + 1);

如果您使用的是 Java 8,则有(可以说)更优雅的语法:

wordCounts.put(word, wordCount.getOrDefault(word, 0) + 1);

wordCounts.merge(word, 1, Integer::sum);

处理完所有文本后,您可以打印出计数:

for (String word: wordCounts.keySet()) {
System.out.println("Word " + word + " occurred " + wordCounts.get(word) + " times";
}

关于java - 如何计算 HashMap 中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43509070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com