Create wordforms using python

拜拜、爱过 提交于 2019-12-23 05:33:05

问题


How can I get different word forms using Python. I want to create a list like the following.

Work=['Work','Working','Works']

My code:

raw = nltk.clean_html(html)
cleaned = re.sub(r'& ?(ld|rd)quo ?[;\]]', '\"', raw)
tokens = nltk.wordpunct_tokenize(cleaned)
stemmer = PorterStemmer()
t = [stemmer.stem(t) if t in Words else t for t in tokens]
text = nltk.Text(t)
word = words(n)
Words = [stemmer.stem(e) for e in word]
find = ' '.join(str(e) for e in Words)
search_words = set(find.split(' '))
sents = ' '.join([s.lower() for s in text])
blob = TextBlob(sents.decode('ascii','ignore'))
matches = [map(str, blob.sentences[i-1:i+2])     # from prev to after next
            for i, s in enumerate(blob.sentences) # i is index, e is element
            if search_words & set(s.words)]
    #return list(itertools.chain(' '.join (str(y).replace('& rdquo','').replace('& rsquo','') for y in matches))
return list(itertools.chain(*matches))

回答1:


It was a little tricky. I tried to look at the stemmed forms in the text and then mapped it with the list of words. Also i changed it to lower case since tokenizing doesn't do that and than it mapped perfectly. Below is the updated code

raw = nltk.clean_html(html)
cleaned = re.sub(r'& ?(ld|rd)quo ?[;\]]', '\"', raw)
tokens = nltk.wordpunct_tokenize(cleaned)
lower = [w.lower() for w in tokens]
stemmer = PorterStemmer()
t = [stemmer.stem(t) if t in Words else t for t in lower]
text = nltk.Text(t)
word = words(n)
Words = [stemmer.stem(e) for e in word]
find = ' '.join(str(e) for e in Words)
search_words = set(find.split(' '))
sents = ' '.join([s.lower() for s in text])
blob = TextBlob(sents.decode('ascii','ignore'))
matches = [map(str, blob.sentences[i-1:i+2])     # from prev to after next
        for i, s in enumerate(blob.sentences) # i is index, e is element
        if search_words & set(s.words)]
#return list(itertools.chain(' '.join (str(y).replace('& rdquo','').replace('& rsquo','') for y in matches))

return list(itertools.chain(*matches))



来源:https://stackoverflow.com/questions/24952690/create-wordforms-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!