java - 对Integer对象进行加操作,从目录中读取多个文件以在Java中创建词袋

标签 java io machine-learning hashmap perceptron

词袋与文档术语矩阵相同吗?

我有一个由许多文件组成的训练数据集。我想将它们全部读入数据结构( HashMap ?),为特定类别的文档(科学、宗教、体育或性)创建词袋模型,为感知器实现做好准备。

现在我有最简单的 Java I/o 结构,即

    String text; 
    BufferedReader br = new BufferedReader(new FileReader("file"));

    while ((text = br.readLine()) != null) 
    {
        //read in multiple files
        //generate a hash map with each unique word
        //as a key and the frequency with which that
        //word appears as the value
    }

所以我想要做的是从一个目录中的多个文件读取输入并将所有数据保存到一个底层结构中,如何做到这一点?我应该将其写到某个文件中吗?

根据我对词袋的理解,我认为 HashMap (正如我在上面代码的注释中所描述的那样)是可行的。是对的吗?我怎样才能通过从多个文件读取输入来实现这样的事情。我应该如何存储它,以便稍后将其合并到我的感知器算法中?

我已经看到了这个完成 like so :

  String names = new String[]{"a.txt", "b.txt", "c.txt"};
  StringBuffer strContent = new StringBuffer("");

  for (String name : names) {
      File file = new File(name); 
      int ch;
      FileInputStream stream = null;  
      try {
          stream = new FileInputStream(file);   
          while( (ch = stream.read()) != -1) {
          strContent.append((char) ch); 
          }
      } finally {
          stream.close();  
      } 
   }

但是这是一个蹩脚的解决方案,因为您需要提前指定所有文件,我认为这应该更加动态。如果可能的话。

最佳答案

您可以尝试下面的程序,它是动态的,您只需要提供您的目录路径。

public class BagOfWords {

ConcurrentHashMap<String, Set<String>> map = new ConcurrentHashMap<String, Set<String>>();

public static void main(String[] args) throws IOException {
    File file = new File("F:/Downloads/Build/");
    new BagOfWords().iterateDirectory(file);
}

private void iterateDirectory(File file) throws IOException {
    for (File f : file.listFiles()) {
        if (f.isDirectory()) {
            iterateDirectory(file);
        } else {
            // Read File
            // Split and put it in a set
            // add to map
        }
    }
}

}

关于java - 对Integer对象进行加操作,从目录中读取多个文件以在Java中创建词袋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28535043/

相关文章:

java - 使用 springfox-swagger2 版本 3.0.0-SNAPSHOT 观察错误 "Unable to infer base url"

Java 实例成员和并发

printing - Lua 在文件读取之前不打印

machine-learning - 径向基函数网络(RBF网络)

python - 简单的多层神经网络实现

java - 具有线性时间复杂度的嵌套循环?

java - 图像构建期间的多线程

java - 无法理解带有 throws 的外部代码

c - 如何确定外围设备的端口号?

python - 神经网络模型没有提高准确性。规模问题还是模型问题?