好吧所以我试图制作一个Map <String, Integer>
,其关键是单词,值是频率。然后使用它我想要Map<String, Map<String, Integer>>
使得键是文档标题,值是具有文档的术语频率的Map。这是我的方法:
private Map<Integer, Map<String, Integer>> findTFs(Set<String> terms)
throws IOException {
// get an iterator for all the terms (words)
TermsEnum termEnum = MultiFields.getTerms(reader, "content").iterator(
null);
//main map
tf = new HashMap<Integer, Map<String, Integer>>();
while (termEnum.next() != null) {
//the parameter "terms" is just the 50 top words of the all documents
if (terms.contains(termEnum.term().utf8ToString())) {
//Document enumerator
DocsEnum docEnum = MultiFields.getTermDocsEnum(reader,
MultiFields.getLiveDocs(reader), "content",
termEnum.term());
int doc = DocsEnum.NO_MORE_DOCS;
int count = 0;
while ((doc = docEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
System.out.println(docEnum.docID() + ": "
//document title
+ reader.document(docEnum.docID()).get("title")
//word
+ ": " + termEnum.term().utf8ToString() + ": "
//frequency
+ docEnum.freq());
}
}
}
return tf
}
我的问题是设置循环使得它们移动到每个单词的下一个文档,并且我一直在努力为每个文档制作单个地图。任何帮助将不胜感激。
答案 0 :(得分:0)
由于您的文档实例取决于术语,您应该将文档添加到主地图中,并使用内部术语频率图。当您继续下一个术语时,您可能会获得另一个文档,您将再次添加到主地图,或者您可能会获得已添加到主地图的文档,在这种情况下,您首先要检查主映射如果包含该文档,如果包含该文档,则只需获取内部术语频率图以进行更新。
这里有一些内部循环的伪代码来说明:
while ((doc = docEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
// Get document title, which is used as a key in the main map
String docTitle = reader.document(docEnum.docID()).get("title");
Map docTermFreq = null;
// If document title already exists in main map
if (tf.containsKey(docTitle)) {
// Get the document term frequency map
docTermFreq = tf.get(docTitle);
} else {
// Create one
docTermFreq = new HashMap<String, Integer>();
// Put it in the main map
tf.put(docTitle, docTermFreq);
}
docTermFreq.put(term, docEnum.freq());
}
外环应保持不变。最后,您只需返回tf
。顺便说一下,您需要更改方法签名以返回Map<String, Map<String, Integer>>
而不是Map<Integer, Map<String, Integer>>