用胭砜烯提取 tf-idf 向量
2022-09-03 08:10:01
我使用lucene索引了一组文档。我还为每个文档内容存储了 DocumentTermVector。我写了一个程序,并为每个文档获取了术语频率向量,但是如何获得每个文档的tf-idf向量?
以下是我的代码,用于在每个文档中输出术语频率:
Directory dir = FSDirectory.open(new File(indexDir));
IndexReader ir = IndexReader.open(dir);
for (int docNum=0; docNum<ir.numDocs(); docNum++) {
System.out.println(ir.document(docNum).getField("filename").stringValue());
TermFreqVector tfv = ir.getTermFreqVector(docNum, "contents");
if (tfv == null) {
// ignore empty fields
continue;
}
String terms[] = tfv.getTerms();
int termCount = terms.length;
int freqs[] = tfv.getTermFrequencies();
for (int t=0; t < termCount; t++) {
System.out.println(terms[t] + " " + freqs[t]);
}
}
在lucene中有什么buit-in功能让我这样做吗?
没有人帮忙,我自己做了:
Directory dir = FSDirectory.open(new File(indexDir));
IndexReader ir = IndexReader.open(dir);
int docNum;
for (docNum = 0; docNum<ir.numDocs(); docNum++) {
TermFreqVector tfv = ir.getTermFreqVector(docNum, "title");
if (tfv == null) {
// ignore empty fields
continue;
}
String tterms[] = tfv.getTerms();
int termCount = tterms.length;
int freqs[] = tfv.getTermFrequencies();
for (int t=0; t < termCount; t++) {
double idf = ir.numDocs()/ir.docFreq(new Term("title", tterms[t]));
System.out.println(tterms[t] + " " + freqs[t]*Math.log(idf));
}
}
有没有办法找到每个术语的ID号?
没有人帮忙,我又自己做了一次:
List list = new LinkedList();
terms = null;
try
{
terms = ir.terms(new Term("title", ""));
while ("title".equals(terms.term().field()))
{
list.add(terms.term().text());
if (!terms.next())
break;
}
}
finally
{
terms.close();
}
int docNum;
for (docNum = 0; docNum<ir.numDocs(); docNum++) {
TermFreqVector tfv = ir.getTermFreqVector(docNum, "title");
if (tfv == null) {
// ignore empty fields
continue;
}
String tterms[] = tfv.getTerms();
int termCount = tterms.length;
int freqs[] = tfv.getTermFrequencies();
for (int t=0; t < termCount; t++) {
double idf = ir.numDocs()/ir.docFreq(new Term("title", tterms[t]));
System.out.println(Collections.binarySearch(list, tterms[t]) + " " + tterms[t] + " " + freqs[t]*Math.log(idf));
}
}