词干提取器索引文本
IndexedText.py文件:
import nltk class IndexedText(object):def __init__(self,stemmer,text):self._text=textself._stemmer=stemmerself._index=nltk.Index((self._stem(word),i) for (i,word) in enumerate(text))def concordance(self,word,width=40):key=self._stem(word)wc=width/4for i in self._index[key]:lcontext=' '.join(self._text[i-wc:i])rcontext=' '.join(self._text[i:i+wc])ldisplay='%*s' % (width,lcontext[-width:])rdisplay='%-*s'% (width,rcontext[:width])print ldisplay,rdisplaydef _stem(self,word):return self._stemmer.stem(word).lower()%-*s 代表輸入一個字符串,-號代表左對齊、后補空白,*號代表對齊寬度由輸入時確定
%*s 代表輸入一個字符串,右對齊、前補空白,*號代表對齊寬度由輸入時確定 輸出的特點是,以lie這個關鍵詞為中心,向左和向右延伸width/4(也就是wc)長度,以此長度來截取文章中的句子,最終輸出到終端。
代碼的作用是,在grail.txt中找出包含有關鍵詞lie的句子。
總結
- 上一篇: NLTK自带的词干提取器
- 下一篇: Your STATICFILES_DIR