java - 文本文件中有多少个唯一单词以及这些唯一单词的计数是多少

标签 java arrays

import java.io.FileReader;
import java.util.Arrays;


public class dictionary {

    public static void main(String[] args) throws IOException {

        // Read all the words from the dictionary (text.txt) into an array
        BufferedReader br = new BufferedReader(new FileReader("text.txt"));
        int bufferLength = 1000000;
        char[] buffer = new char[bufferLength];
        int charsRead = br.read(buffer, 0, bufferLength);
        br.close();
        String text = new String(buffer);
        text = text.trim();
        text = text.toLowerCase();
        String[] words = text.split("\n");

        System.out.println("Total number of words in text: " + words.length);

        //to find for unique text
        String[] uniqueText = {};
        int[] textCount = new int[uniqueText.length];

        for (int i = 0; i < words.length; i++) {

            if (uniqueText[i].contains(words[i])) {
                textCount[i]++;

            } else {
                uniqueText[i] = words[i];

            }

        }
    }

嗨,我无法在这里弄清楚我的代码,而且我真的不知道如何用语言表达我的问题,所以我将使用伪代码。

线程“main”java.lang.NullPointerException 中出现异常

if (uniqueText[i].contains(words[i]))

create a string array [uniqueText]
create an int array [uniqueTextCount]

   For every word in text

      if word[i] exists in uniqueText(
            +uniqueTextCount[i])
      else(
           + the new unique word to uniqueText)

最佳答案

这里的问题是您正在初始化一个空白数组,String[] uniqueText = {};,然后尝试添加到该数组(uniqueText[i] = Words[我];)。我相信您正在寻找类似 List 的东西,其中大小可以是动态的,因为我们从一开始就不知道有多少个独特的单词。或者我们甚至可以更进一步,使用一个 Map,它也具有动态大小,但使用键和值,非常适合这种情况,因为我们希望将单词链接到计数。

System.out.println("Total number of words in text: " + words.length);

Map<String, Integer> uniqueWordsAndCount = new HashMap<>();
for (String word : words) { 
    if (uniqueWordsAndCount.containsKey(word)){ //If word is in our map already, increase count
        uniqueWordsAndCount.put(word, uniqueWordsAndCount.get(word)+1);
    }else{  //If not in our map, add it and set count to 1
        uniqueWordsAndCount.put(word, 1);
    }
} 
//Accessing the count of a word
uniqueWordsAndCount.get("someWord"); //This returns the count

关于java - 文本文件中有多少个唯一单词以及这些唯一单词的计数是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923266/

相关文章:

python - 如何在 numpy 中添加计算/计算列?

javascript - JS 函数在控制台中给我未定义的信息,但我期待一个数字

java - Switch 语句无法识别字段变量

java - 为什么我第一次运行此应用程序时不断收到 NullPointer 错误?

java - nginx作为Websocket代理发送短信

javascript - $lookup 深度嵌套对象

java - Spring:将@RequestBody 注入(inject)@Bean

java - 多个模块的 GWT 欢迎文件

c - ISO C 禁止在 C 中使用空的初始化大括号

Java:将字符串数组项解析为 int、double 或 string