удаление биграмм, содержащих общие стоп-слова - PullRequest
0 голосов
/ 07 марта 2020

У меня есть функция, как показано ниже. Возвращает все биграммы и триграммы в предложении. Я хотел бы сохранить только биграммы и триграммы, которые не содержат стоп-слов. Как я могу использовать from nltk.copus import stopwords, чтобы сделать то же самое?

Я знаю, как удалить стоп-слова перед созданием биграмм и триграмм. Но я хотел бы удалить стоп-слова после создания биграмм и триграмм.

from nltk import everygrams
from nltk.copus import stopwords


def clean_text_function2(text):
    t = text #contractions.fix(text)
    t= t.lower().split()#lower case
    t = [(re.sub(r'[^a-z ]', '', ch)) for ch in t]#remove everything other than a-z
    #t=[word for word in t if word not in stopword]#removing stop words
    t= [wordnet_lemmatizer.lemmatize(word) for word in t]
    t=[snowball_stemmer.stem(word) for word in t]
    t=(' ').join(t)
    t=list(everygrams(t.split(), 2, 3))
    return t






print (clean_text_function2("i love when it rains a lot and brings temperature down"))

[('i', 'love'), ('love', 'when'), ('when', 'it'), ('it', 'rain'), ('rain', 'a'), ('a', 'lot'), ('lot', 'and'), ('and', 'bring'), ('bring', 'temperatur'), ('temperatur', 'down'), ('i', 'love', 'when'), ('love', 'when', 'it'), ('when', 'it', 'rain'), ('it', 'rain', 'a'), ('rain', 'a', 'lot'), ('a', 'lot', 'and'), ('lot', 'and', 'bring'), ('and', 'bring', 'temperatur'), ('bring', 'temperatur', 'down')]

1 Ответ

1 голос
/ 07 марта 2020

Создайте фильтр, сохраняя только те кортежи, у которых нет стоп-слов. Я буду слишком многословен, чтобы убедиться, что техника читаема.

Для каждого грамма используйте any, чтобы проверить наличие любого из заданных стоп-слов.

grams = [('i', 'love'), ('love', 'when'), ('when', 'it'), ('it', 'rain'), ('rain', 'a'), ('a', 'lot'), ('lot', 'and'), ('and', 'bring'), ('bring', 'temperatur'), ('temperatur', 'down'), ('i', 'love', 'when'), ('love', 'when', 'it'), ('when', 'it', 'rain'), ('it', 'rain', 'a'), ('rain', 'a', 'lot'), ('a', 'lot', 'and'), ('lot', 'and', 'bring'), ('and', 'bring', 'temperatur'), ('bring', 'temperatur', 'down')]
stops = ["a", "and", "it", "the"]

clean = [gram for gram in grams if not any(stop in gram for stop in stops)]
print(clean)

Вывод:

[('i', 'love'), ('love', 'when'), ('bring', 'temperatur'), ('temperatur', 'down'), ('i', 'love', 'when'), ('bring', 'temperatur', 'down')]
...