Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ngram features extractor using spacy #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions scattertext/features/FeatsFromSpacyNgrams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from collections import Counter

from cytoolz.itertoolz import sliding_window

from scattertext import FeatsFromSpacyDoc


class FeatsFromSpacyDocMultiGrams(FeatsFromSpacyDoc):
def __init__(self, ngrams, pos_as_tag=None):
super(FeatsFromSpacyDocMultiGrams, self).__init__()
self.pos_as_tag = pos_as_tag
self.ngrams = ngrams

def get_feats(self, doc):
ngrams_counter = Counter()
for sent in doc.sents:
words = self._get_unigram_feats(sent)
for ngrams in self._get_ngram_feats(words):
ngrams_counter += Counter(ngrams)
return ngrams_counter

def _get_ngram_feats(self, words):
for ngram in self.ngrams:
if len(words) >= ngram:
yield map(' '.join, sliding_window(ngram, words))

def _get_unigram_feats(self, sent):
return [
tok.text.strip() if tok.pos_ not in self.pos_as_tag else tok.pos_
for tok
in sent
]