java 倒排索引 行数_倒排索引的java实现

假设有3篇文章,file1, file2, file3,文件内容如下:

文件内容代码

9bae34d55f313a52068303f710150ab9.png

file1 (单词1,单词2,单词3,单词4....)

file2 (单词a,单词b,单词c,单词d....)

file3 (单词1,单词a,单词3,单词d....)

那么建立的倒排索引就是这个样子:

文件内容代码

9bae34d55f313a52068303f710150ab9.png

单词1 (file1,file3)

单词2 (file1)

单词3 (file1,file3)

单词a (file2, file3)

....

而词频就是每个单词在文件中出现的相应次数,本文计算的是每个单词在所有文件中出现的总次数,如果有更简洁有效的写法,欢迎交流。

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

public class IntertedIndex {

private Map> map=new HashMap<>();

private ArrayList list;

private Map nums=new HashMap<>();

public void CreateIndex(String filepath){

String[] words = null;

try {

File file=new File(filepath);

BufferedReader reader=new BufferedReader(new FileReader(file));

String s=null;

while((s=reader.readLine())!=null){

//获取单词

words=s.split(" ");

}

for (String string : words) {

if (!map.containsKey(string)) {

list=new ArrayList();

list.add(filepath);

map.put(string, list);

nums.put(string, 1);

}else {

list=map.get(string);

//如果没有包含过此文件名,则把文件名放入

if (!list.contains(filepath)) {

list.add(filepath);

}

//文件总词频数目

int count=nums.get(string)+1;

nums.put(string, count);

}

}

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

IntertedIndex index=new IntertedIndex();

for(int i=1;i<=3;i++){

String path="E:\\data\\"+i+".txt";

index.CreateIndex(path);

}

for (Map.Entry> map : index.map.entrySet()) {

System.out.println(map.getKey()+":"+map.getValue());

}

for (Map.Entry num : index.nums.entrySet()) {

System.out.println(num.getKey()+":"+num.getValue());

}

}

}文件内容:

1.txt:i live in hangzhou where are you

2.txt:i love you i love you

3.txt:i love you today is a good day

运行结果

f043f1ec5fe793efc6c31f02050c4f54.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值