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("baiduqa.py")
printIndex(index)
print indexQuery(index, "in", "enumerate")
追问:
filename baiduqa.py
追答:
makeIndex函数接收一个文件名作为参数,读取文件中的字符串; 在上面的例子里,将“baiduqa.py"作为要解读的文本文件。你可以将之换成你的数据文件
追问:
这个能输入一个单词 然后再进行查询吗
追答:
def makeIndex(filename):
index, lineno = {}, 0
while True:
line = raw_input()
if line:
for word in patt.findall(ln):
index.setdefault(word, []).append(i+1)
else:
break
return index
追问:
能和上面并一起吗,我比较菜
追答:
import re
patt = re.compile("\w+")
def makeIndex():
index, lineno = {}, 0
while True:
ln = raw_input()
if ln:
lineno += 1
for word in patt.findall(ln):
index.setdefault(word, []).append(lineno)
else:
break
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()
printIndex(index)
while True:
ln = raw_input()
words = patt.findall(ln)
if words:
print indexQuery(index, *words)
else:
break
作业帮用户
2017-09-20
举报