python倒排索引(Inverted index)
发布网友
发布时间:2022-04-21 15:31
我来回答
共1个回答
热心网友
时间:2023-11-14 20:18
s = raw_input()
lines = s.split('\n')
dictlines = lines[:100]
mydict = {}
# read
for i,line in enumerate(dictlines ):
for word in line.split():
mydict.setdefault(word,[]).append(i + 1)
# print indices
for word in mydict.keys():
print "%s: %s" % (word,", ".join(map(str,sorted(mydict[word]))))
def andSearch(words_list):
global mydict
a = set(range(1,101))
for word in words_list:
a = a.intersection(set(mydict[word]))
return a
def orSearch(words_list):
global mydict
a = set([])
for word in words_list:
a = a.union(set(mydict[word]))
return a
# Query
index = 100
u = lines[index]
while index < len(lines):
words_list = u.split()
if ":" in u:
if words_list[0] == "OR:":
a = orSearch(words_list)
else:
if words_list[0] == 'AND:':
words_list = words_list[1:]
a = andSearch(words_list)
if not a:
print ", ".join(map(str,list(a)))
else:
print "None"
index += 1
大致思想就是这样。。。。。。。。