python 實現(xiàn)倒排索引的方法
更新時間:2018年12月25日 09:49:35 作者:濤濤不絕蕾蕾于冬
今天小編就為大家分享一篇python 實現(xiàn)倒排索引的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
代碼如下:
#encoding:utf-8 fin = open('1.txt', 'r') ''' 建立正向索引: “文檔1”的ID > 單詞1:出現(xiàn)位置列表;單詞2:出現(xiàn)位置列表;………… “文檔2”的ID > 此文檔出現(xiàn)的關鍵詞列表。 ''' forward_index = {} for line in fin: line = line.strip().split() forward_index[int(line[0])] = {} words = line[1].split(',') for i, index in enumerate(words): if int(index) not in forward_index[int(line[0])].keys(): forward_index[int(line[0])][int(index)] = [i] else: forward_index[int(line[0])][int(index)].append(i) print 'forward_index:', forward_index ''' 建立倒排索引: “關鍵詞1”:“文檔1”的ID,“文檔2”的ID,………… “關鍵詞2”:帶有此關鍵詞的文檔ID列表。 ''' inverted_index = {} for doc_id, words in forward_index.items(): for word_id in words.keys(): if word_id not in inverted_index.keys(): inverted_index[word_id] = [doc_id] elif doc_id not in inverted_index[word_id]: inverted_index[word_id].append(doc_id) print 'inverted_index:', inverted_index
輸入(文檔id:單詞id):
1 3,4 2 3,4,2,4 3 2
輸出:
forward_index: {1: {3: [0], 4: [1]}, 2: {2: [2], 3: [0], 4: [1, 3]}, 3: {2: [0]}} inverted_index: {2: [2, 3], 3: [1, 2], 4: [1, 2]}
以上這篇python 實現(xiàn)倒排索引的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
matplotlib部件之矩形選區(qū)(RectangleSelector)的實現(xiàn)
這篇文章主要介紹了matplotlib部件之矩形選區(qū)(RectangleSelector)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02Python通過wordcloud庫實現(xiàn)將單詞生成詞云
Python的wordcloud庫是一個用于生成詞云的Python包,它可以將一段文本中出現(xiàn)頻率高的單詞按其出現(xiàn)頻率大小以及顏色深淺排列成一個詞云圖形,從而更好地展示文本中的信息,你可以使用wordcloud庫來生成各種類型的詞云,本文就介紹了如何生成心型詞云2023-06-06Django 實現(xiàn) Websocket 廣播、點對點發(fā)送消息的代碼
這篇文章主要介紹了Django 實現(xiàn) Websocket 廣播、點對點發(fā)送消息,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06pandas讀取HTML和JSON數(shù)據(jù)的實現(xiàn)示例
Pandas可以直接讀取html和JSON數(shù)據(jù),本文就來介紹一下pandas讀取HTML和JSON數(shù)據(jù)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,感興趣的可以了解一下2024-01-01