datadabllp

inverted index

Jul 19th, 2024
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. class InvertedIndex:
  2.     def __init__(self):
  3.         self.index = {}
  4.  
  5.     def add_document(self, doc_id, content):
  6.         words = content.lower().split()
  7.         for word in words:
  8.             if word not in self.index:
  9.                 self.index[word] = set()
  10.             self.index[word].add(doc_id)
  11.  
  12.     def search(self, query):
  13.         query_words = query.lower().split()
  14.         result = set.intersection(*[self.index.get(word, set()) for word in query_words])
  15.         return list(result)
  16.  
  17. # Usage
  18. index = InvertedIndex()
  19. index.add_document(1, "Java performance tuning techniques")
  20. index.add_document(2, "Optimizing JVM for high throughput")
  21. index.add_document(3, "Python vs Java: A performance comparison")
  22.  
  23. print(index.search("java performance"))  # Output: [1, 3]
  24.  
Advertisement
Add Comment
Please, Sign In to add comment