展开全部
$ python baidu_qa.py
Enter Context, leave by empty line
def __init__(self, datafile, default=None):
self.datafile = datafile
self.default = default
self.data = shelve.BsdDbShelf(bsddb.open(self.datafile, 'c'))
def __del__(self):
self.data.sync()
self.data.close()
def __getitem__(self, k):
return self.data.get(k, self.default)
def __setitem__(self, k, v):
self.data[k] = v
Enter and/or keywords to query
and default data
[9]
or get k v
[8, 9, 10, 11]
$# coding: utf-8
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 indexAndQuery(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)
def indexOrQuery(index, *args):
found = set()
for word in args:
found |= set(index.get(word, []))
return list(found)
def lnparser(ln):
words = patt.findall(ln.lower())
if len(words)<2 or words[0] not in ('and','or'):
# 输入的62616964757a686964616fe78988e69d8331333332643335行不是以and, or开始, 或未给出待查单词
return None
else:
return words[0], words[1:]
cmdswitch = {
'and': indexAndQuery,
'or': indexOrQuery,
}
print "Enter Context, leave by empty line"
index = makeIndex()
print "Enter and/or keywords to query"
while True:
got = lnparser(raw_input())
if not got:
break
print cmdswitch[got[0]](index, *got[1])