倒排索引,我可以在其中保存单词的元组以及它来自哪里的 id
Inverted Index where I can save a tuple of the word along with an id of where it came from
我创建了以下 class 以在 Python 中实现倒排索引。我阅读了 quora 问题对挑战中的问题。问题是这样的形式:
---------------------------
qid |question
---------------------------
1 |Why do we exist?
2 |Is there life on Mars?
3 |What happens after death?
4 |Why are bananas yellow?
问题是我希望 qid 与倒排索引中的每个单词一起传递,以便在创建它后我知道每个单词来自哪个问题,并轻松访问它。
class Index:
""" Inverted index datastructure """
def __init__(self):
self.index = defaultdict(list)
self.documents = {}
self.__unique_id = 0
def lookup(self, word):
"""
Lookup a word in the index
"""
word = word.lower()
if self.stemmer:
word = self.stemmer.stem(word)
return [self.documents.get(id, None) for id in self.index.get(word)]
def addProcessed(self, words):
"""
Add a document string to the index
"""
for word in words:
if self.__unique_id not in self.index[word]:
self.index[word].append(self.__unique_id)
self.documents[self.__unique_id] = words
self.__unique_id += 1
如何在我的上述数据结构中实现它?
将 qid
放入索引的一种直接方法是编写 Index.addProcessed
以接收 qid
作为第二个参数,并将其包含在 unique_id
的值集中键入文档。
def addProcessed(self, words, qid):
#...
self.documents[self.__unique_id] = (words, qid)
self.__unique_id += 1
Index.lookup
将 return 由单词及其问题 ID 组成的元组列表。
我创建了以下 class 以在 Python 中实现倒排索引。我阅读了 quora 问题对挑战中的问题。问题是这样的形式:
---------------------------
qid |question
---------------------------
1 |Why do we exist?
2 |Is there life on Mars?
3 |What happens after death?
4 |Why are bananas yellow?
问题是我希望 qid 与倒排索引中的每个单词一起传递,以便在创建它后我知道每个单词来自哪个问题,并轻松访问它。
class Index:
""" Inverted index datastructure """
def __init__(self):
self.index = defaultdict(list)
self.documents = {}
self.__unique_id = 0
def lookup(self, word):
"""
Lookup a word in the index
"""
word = word.lower()
if self.stemmer:
word = self.stemmer.stem(word)
return [self.documents.get(id, None) for id in self.index.get(word)]
def addProcessed(self, words):
"""
Add a document string to the index
"""
for word in words:
if self.__unique_id not in self.index[word]:
self.index[word].append(self.__unique_id)
self.documents[self.__unique_id] = words
self.__unique_id += 1
如何在我的上述数据结构中实现它?
将 qid
放入索引的一种直接方法是编写 Index.addProcessed
以接收 qid
作为第二个参数,并将其包含在 unique_id
的值集中键入文档。
def addProcessed(self, words, qid):
#...
self.documents[self.__unique_id] = (words, qid)
self.__unique_id += 1
Index.lookup
将 return 由单词及其问题 ID 组成的元组列表。