字符串for循环不能选择粒度/list可以 一般操作是将一个字符串分词放入一个字符串list中 将结果写入一个文件或终端时,格式化为一个字符串
字符串不可修改
不要忘记\ , {}, (), |
# 提取字符块 import re re.findall(r'regexp', word) #找到所有满足regexp的字符 # 查找词干 def stem(word): regexp = r'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)?$' stem, tuffix = re.findall(regexp, word)[0] return stem # 搜索已分词文本 mody = nltk.Text(corpus.words('txt')) mody.findall(r''<a> (<.*>) <man>'') #返回中间词,e.g. naive mody.findall(r''<.*>,<.*>,<bro>") #返回以bro结尾的三个词。词形归并
一般而言,优先适用NLTK中的词干提取器而非正则表达式过滤。
class IndexedText(object): def __init__(self, stemmer, text): self._text = text self._stemmer = stemmer self._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/4 for 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, rdisplay def _stem(self, word): return self._stemmer.stem(word).lower()