如何用Python建立索引
发布网友
发布时间:2022-04-25 15:49
我来回答
共1个回答
热心网友
时间:2022-04-07 13:07
import re
patt = re.compile("\w+")
def makeIndex(filename):
index = {}
with open(filename) as handle:
for i, ln in enumerate(handle):
for word in patt.findall(ln):
index.setdefault(word, []).append(i+1)
return index
def printIndex(index):
for word, lst in index.items():
print "%s: %s" % (
word, ", ".join(map(str, lst))
)
def indexQuery(index, *args):
found = None
for word in args:
got = index.get(word, [])
if not got:
return None
if not found:
found = set(got)
else:
found &= set(got)
if not found:
return None
return list(found)
index = makeIndex("qa.py")
printIndex(index)
print indexQuery(index, "in", "enumerate")