當前位置:編程學習大全網 - 編程軟體 - 如何用Python建立索引

如何用Python建立索引

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")

  • 上一篇:現年22歲,女性。學歷不高,可以學IT嗎?
  • 下一篇:Java2遊戲編程
  • copyright 2024編程學習大全網