[英]list intersection algorithm implementation only using python lists (not sets)
[英]Python: intersection of lists/sets
def boolean_search_and(self, text):
results = [] and_tokens = self.tokenize(text) tokencount = len(and_tokens) term1 = and_tokens[0] print ' term 1:', term1 term2 = and_tokens[1] print ' term 2:', term2 #for term in and_tokens: if term1 in self._inverted_index.keys(): resultlist1 = self._inverted_index[term1] print resultlist1 if term2 in self._inverted_index.keys(): resultlist2 = self._inverted_index[term2] print resultlist2 #intersection of two sets casted into a list results = list(set(resultlist1) & set(resultlist2)) print 'results:', results return str(results)
此代碼非常適合兩個令牌,例如:text =“ Hello World”,因此,令牌= ['hello','world']。 我想將其概括為多個標記,因此文本可以是句子,也可以是整個文本文件。
self._inverted_index是一個字典,將令牌另存為密鑰,而值是其中出現密鑰/令牌的DocID。
你好-> [1,2,5,6]
世界-> [1,3,5,7,8]
結果:
你好,世界-> [1,5]
我想取得以下結果:((((hello AND computer)AND science)AND world)
我正在努力使此詞適用於多個單詞,而不僅僅是兩個單詞。 我從今早開始使用python工作,所以我不知道它必須提供的許多功能。
有任何想法嗎?
我想將其概括為多個令牌
def boolean_search_and_multi(self, text):
and_tokens = self.tokenize(text)
results = set(self._inverted_index[and_tokens[0]])
for tok in and_tokens[1:]:
results.intersection_update(self._inverted_index[tok])
return list(results)
內置set類型適合您嗎?
$ python
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> hello = set([1,2,5,6])
>>> world = set([1,3,5,7,8])
>>> hello & world
set([1, 5])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.