词袋与文档术语矩阵相同吗?
我有一个由许多文件组成的训练数据集。我想将它们全部读入数据结构( 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/