1. 程式人生 > >倒排索引的java實現

倒排索引的java實現

 假設有3篇文章,file1, file2, file3,檔案內容如下: 

檔案內容程式碼  收藏程式碼
  1. file1 (單詞1,單詞2,單詞3,單詞4....)  
  2. file2 (單詞a,單詞b,單詞c,單詞d....)  
  3. file3 (單詞1,單詞a,單詞3,單詞d....)  

    那麼建立的倒排索引就是這個樣子:

檔案內容程式碼  收藏程式碼
  1. 單詞1 (file1,file3)  
  2. 單詞2 (file1)  
  3. 單詞3 (file1,file3)  
  4. 單詞a (file2, file3)  
  5. ....  

而詞頻就是每個單詞在檔案中出現的相應次數,本文計算的是每個單詞在所有檔案中出現的總次數,如果有更簡潔有效的寫法,歡迎交流。

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<String, ArrayList<String>> map=new HashMap<>();
	private ArrayList<String> list;
	private Map<String, Integer> 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<String>();
					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<String, ArrayList<String>> map : index.map.entrySet()) {
			System.out.println(map.getKey()+":"+map.getValue());
		}

		for (Map.Entry<String, Integer> 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

執行結果