python检索_python如何高级检索

展开全部

$ 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])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值