您的位置:首页 > 其它

正则表达式的相关应用

2018-03-24 19:35 197 查看
1.通过re.findall()方法找出所有匹配的指定的正则表达式。例如:找出以下示例词中的所有元音,并计数。>>> word='supercalifragilisticexpialidocious'
>>> re.findall(r'[aeiou]',word)
['u', 'e', 'a', 'i', 'a', 'i', 'i', 'i', 'e', 'i', 'a', 'i', 'o', 'i', 'o', 'u']
>>> len(re.findall(r'[aeiou]',word))
16
>>> 2.查找文本中两个或两个以上的元音序列,并确定他们的相对频率。wsj=sorted(set(nltk.corpus.treebank.words()))
... fd= nltk.FreqDist(vs for word in wsj for vs in re.findall(r'[aeiou]{2,}',word))
>>> fid.items()3.将正则表达式与条件频率分布结合起来。例子中,从罗托卡特语词汇中提取所有的辅音-元音序列,如ka和si,因为其都是成对出现的,所以可以用频率分布表来表示。>>> rotokas_words=nltk.corpus.toolbox.words('rotokas.dic')
>>> cvs=[cv for w in rotokas_words for cv in re.findall(r'[ptksvr][aeiou]',w)]
>>> cfd=nltk.conditionalFreqDist(cvs)
>>> cfd.tabulate()4.查找词干
apples和apple对比中,apple就是词干。写一个简单脚本来查询词干。
def stem(word):
for suffix in ['ing','ly','ed','ious','ies','ive','es','s','ment']:
if word.endswith(suffix):
return word[:-len(suffix)]
return None而如果利用正则表达式,此问题将会变得很简单re.findall(r'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)$',word)
5.词干提取器和归并器
nltk提供了
PorterStemmer
 和 
LancasterStemmer
两个词干提取器,Porter比较好,可以处理lying这样的单词。
porter = nltk.PorterStemmer()
print(porter.stem('lying'))如果需要处理像women这样的词,需要词性归并器:WordNetLemmatizerwnl = nltk.WordNetLemmatizer()
print(wnl.lemmatize('women'))6.利用词干提取器实现索引文本(concordance)

利用到nltk.Index这个函数,
nltk.Index((word , i) for (i,word) in enumerate(['a','b','a']))
class IndexText:
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 _stem(self,word):
return self._stemmer.stem(word).lower()
def concordance(self,word,width =40):
key = self._stem(word)
wc = width/4 #words of context
for i in self._index[key]:
lcontext = ' '.join(self._text[int(i-wc):int(i)])
rcontext = ' '.join(self._text[int(i):int(i+wc)])
ldisplay = '%*s' % (width,lcontext[-width:])
rdisplay = '%-*s' % (width,rcontext[:width])
print(ldisplay,rdisplay)
porter = nltk.PorterStemmer()
grail = nltk.corpus.webtext.words('grail.txt')
text = IndexText(porter,grail)
text.concordance('lie')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: