2015-08-05 6 views
0

У меня есть простое предложение, подобное этому. Я хочу отказаться от предлогов и слов, таких как A и IT вне списка. Я просмотрел документацию Natural Language Toolkit (NLTK), но ничего не могу найти. Может ли кто-нибудь показать мне, как? Вот мой код:Удаление определенных слов из распределения NLTK за пределами временных слов

import nltk 
from nltk.tokenize import RegexpTokenizer 
test = "Hello, this is my sentence. It is a very basic sentence with not much information in it" 
test = test.upper() 
tokenizer = RegexpTokenizer(r'\w+') 
tokens = tokenizer.tokenize(test) 
fdist = nltk.FreqDist(tokens) 
common = fdist.most_common(100) 
+1

Я думаю, вы имеете в виду предлоги, а не предложения? – tripleee

+0

Возможный дубликат [Удаление стоп-слова с помощью NLTK] (http://stackoverflow.com/questions/19130512/stopword-removal-with-nltk) – alvas

ответ

2

По существу, nltk.probability.FreqDist является объектом collections.Counter (https://github.com/nltk/nltk/blob/develop/nltk/probability.py#L61). Учитывая объект словаря, есть несколько способ фильтрации его:

1. Прочитайте в FreqDist и фильтровать его с помощью лямбда-функции

>>> import nltk 
>>> text = "Hello, this is my sentence. It is a very basic sentence with not much information in it" 
>>> tokenized_text = nltk.word_tokenize(text) 
>>> stopwords = nltk.corpus.stopwords.words('english') 
>>> word_freq = nltk.FreqDist(tokenized_text) 
>>> dict_filter = lambda word_freq, stopwords: dict((word,word_freq[word]) for word in word_freq if word not in stopwords) 
>>> filtered_word_freq = dict_filter(word_freq, stopwords) 
>>> len(word_freq) 
17 
>>> len(filtered_word_freq) 
8 
>>> word_freq 
FreqDist({'sentence': 2, 'is': 2, 'a': 1, 'information': 1, 'this': 1, 'with': 1, 'in': 1, ',': 1, '.': 1, 'very': 1, ...}) 
>>> filtered_word_freq 
{'information': 1, 'sentence': 2, ',': 1, '.': 1, 'much': 1, 'basic': 1, 'It': 1, 'Hello': 1} 

2. Читать в FreqDist и фильтровать его с словарь понимание

>>> word_freq 
FreqDist({'sentence': 2, 'is': 2, 'a': 1, 'information': 1, 'this': 1, 'with': 1, 'in': 1, ',': 1, '.': 1, 'very': 1, ...}) 
>>> filtered_word_freq = dict((word, freq) for word, freq in word_freq.items() if word not in stopwords) 
>>> filtered_word_freq 
{'information': 1, 'sentence': 2, ',': 1, '.': 1, 'much': 1, 'basic': 1, 'It': 1, 'Hello': 1} 

3. Фильтр слов перед чтением в FreqDist

>>> import nltk 
>>> text = "Hello, this is my sentence. It is a very basic sentence with not much information in it" 
>>> tokenized_text = nltk.word_tokenize(text) 
>>> stopwords = nltk.corpus.stopwords.words('english') 
>>> filtered_tokenized_text = [word for word in tokenized_text if word not in stopwords] 
>>> filtered_word_freq = nltk.FreqDist(filtered_tokenized_text) 
>>> filtered_word_freq 
FreqDist({'sentence': 2, 'information': 1, ',': 1, 'It': 1, '.': 1, 'much': 1, 'basic': 1, 'Hello': 1}) 
3

Может stopwords быть решением, которое вы ищете?

Вы можете фильтровать их довольно легко из лексического текста:

from nltk.probability import FreqDist 
from nltk.tokenize import RegexpTokenizer 
from nltk.corpus import stopwords 

en_stopws = stopwords.words('english') # this loads the default stopwords list for English 
en_stopws.append('spam') # add any words you don't like to the list 

test = "Hello, this is my sentence. It is a very basic sentence with not much information in it but a lot of spam" 
test = test.lower() # I changed it to lower(), since stopwords are all lower case 
tokenizer = RegexpTokenizer(r'\w+') 
tokens = tokenizer.tokenize(test) 
tokens = [token for token in tokens if token not in en_stopws] # filter stopwords 
fdist = FreqDist(tokens) 
common = fdist.most_common(100) 

я не нашел хороший способ удаления записей из FreqDist, если вы нашли что-то дайте мне знать.

+0

Я получаю обратную ошибку трассировки ... 'Файл 'C: \ Python27 \ lib \ site-packages \ nltk \ data.py ", строка 293, в __init__ повысить IOError ('Нет такого файла или каталога:% r'% _path) IOError: Нет такого файла или каталога: u'C: \ \ Users \\ jason \\ AppData \\ Роуминг \\ nltk_data \\ corpora \\ stopwords \\ IS'', используя слово 'IS', но я вижу ваш подход к фильтрации до того, как он войдет в – jason

+1

@jason_cant_code. Я думаю, вы неправильно поняли погрузка корпуса секундомера. Я отредактировал и попытался сделать это немного яснее. Также проверьте [книгу] (http://www.nltk.org/book/ch02.html#wordlist-corpora) для получения дополнительной информации – b3000

Смежные вопросы