gpt4 book ai didi

java - java中如何统计tax中某个关键字出现了多少次?

转载 作者:行者123 更新时间:2023-11-29 07:54:00 25 4
gpt4 key购买 nike

问题一:

我正在尝试计算关键字的频率,我的代码有效,但它也计算在内那些也包含关键字的词(例如,如果我搜索“count”,“account”之类的词也会被计算在内。)有人知道如何解决这个问题吗?

问题二:

我还想计算文本中唯一单词的数量(这意味着我只计算重复单词一次)。我也不知道如何实现这一目标。我的代码只给出总字数。

这是我的代码:

import java.util.Scanner;


public class Text_minining {

/**
* @param args
*/
public static void main(String[] args) {

//Prompt the user for the search word
System.out.print("enter a search word: ");
//Get the user's search word input
Scanner keywordScanner = new Scanner(System.in);
String keyword = keywordScanner.nextLine();
keyword = keyword.toLowerCase();

//Prompt the user for the text
System.out.println("Enter a string of words (words separated by single spaces or tabs): ");
//Get the user's string input
Scanner userInputScanner = new Scanner(System.in);
String userInput = userInputScanner.nextLine();
userInput = userInput.toLowerCase();

int keywordCount = 0, wordCount = 0;
int lastIndex = 0;

while(lastIndex != -1){
lastIndex = userInput.indexOf(keyword,lastIndex);
if(lastIndex != -1){
keywordCount ++;
lastIndex = keyword.length() + lastIndex;
}
}

boolean wasSpace=true;
for (int i = 0; i < userInput.length(); i++)
{
if (userInput.charAt(i) == ' ') {
wasSpace=true;
}
else{
if(wasSpace == true) wordCount++;
wasSpace = false;
}
}

//Print the results to the screen
System.out.println("-------");
System.out.println("Good, \"" + keyword + "\"appears in the text and the word count is " + keywordCount);
System.out.println("The total number of unique words in the text is " + wordCount);


System.exit(0);
}
}

最佳答案

首先:userInput.split(keyword).length - 1 可以解决问题。我们使用正则表达式。

第二个:

Set<String> uniqueWords = new HashSet<String>();
for (String word : userInput.split(" ")) {
uniqueWords.add(word);
}
System.out.println("Unique words count " + uniqueWords.size());

关于java - java中如何统计tax中某个关键字出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187859/

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