Как отфильтровать неанглийские данные из CSV с помощью панд - PullRequest
0 голосов
/ 27 декабря 2018

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

import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.feature_extraction.text import CountVectorizer, 
TfidfVectorizer
from sklearn.model_selection import train_test_split, KFold
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
import matplotlib
from matplotlib import pyplot as plt
import sys
sys.setrecursionlimit(100000)
# import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

data = pd.read_csv("C:\\Users\\Administrator\\Desktop\\nlp_dataset\\commitment.csv", encoding='cp1252',na_values=" NaN")

data.shape
data['text'] = data.fillna({'text':'none'})
def remove_punctuation(text):
    '' 'a function for removing punctuation'''
    import string
    #replacing the punctuations with no space,
    #which in effect deletes the punctuation marks
    translator = str.maketrans('', '', string.punctuation)
    #return the text stripped of punctuation marks
    return text.translate(translator)

#Apply the function to each examples 
data['text'] = data['text'].apply(remove_punctuation)
data.head(10)

#Removing stopwords -- extract the stopwords
#extracting the stopwords from nltk library
sw= stopwords.words('english')
#displaying the stopwords
np.array(sw)

# function to remove stopwords
def stopwords(text):
    '''a function for removing stopwords'''
        #removing the stop words and lowercasing the selected words
        text = [word.lower() for word in text.split()  if word.lower() not in sw]
        #joining the list of words with space separator
        return  " ". join(text)

# Apply the function to each examples
data['text'] = data ['text'].apply(stopwords)
data.head(10)

# Top words before stemming  
# create a count vectorizer object
count_vectorizer = CountVectorizer()
# fit the count vectorizer using the text dta
count_vectorizer.fit(data['text'])
# collect the vocabulary items used in the vectorizer
dictionary = count_vectorizer.vocabulary_.items() 

#store the vocab and counts in a pandas dataframe
vocab = []
count = []
#iterate through each vocav and count append the value to designated lists
for key, value in dictionary:
 vocab.append(key)
 count.append(value)
#store the count in pandas dataframe with vocab as indedx
vocab_bef_stem = pd.Series(count, index=vocab)
#sort the dataframe
vocab_bef_stem = vocab_bef_stem.sort_values(ascending = False)

# Bar plot of top words before stemming
top_vocab = vocab_bef_stem.head(20)
top_vocab.plot(kind = 'barh', figsize=(5,10), xlim = (1000, 5000))

Я хочу список часто встречающихся слов, упорядоченных по гистограмме, но сейчас он просто дает неанглийские слова с одинаковой частотой.Пожалуйста, помогите мне

1 Ответ

0 голосов
/ 28 декабря 2018

Проблема в том, что вы не сортируете свой словарь по количеству, а по уникальному идентификатору, созданному векторизатором счета.

count_vectorizer.vocabulary_.items() 

Не содержит счетчик каждой функции.count_vectorizer не сохраняет количество каждой функции.

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

По умолчанию tf-idf удаляет пунктуацию, а также вы можете передать список стоп-слов для векторизатора, который нужно удалить.Ваш код может быть уменьшен следующим образом.

from sklearn.feature_extraction.text import CountVectorizer
corpus = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document ?',
]

sw= stopwords.words('english')

count_vectorizer = CountVectorizer(stop_words=sw)
X = count_vectorizer.fit_transform(corpus)
vocab = pd.Series( X.toarray().sum(axis=0), index = count_vectorizer.get_feature_names())
vocab.sort_values(ascending=False).plot.bar(figsize=(5,5), xlim = (0, 7))

Вместо corpus подключите столбец текстовых данных.Результат вышеупомянутого фрагмента будет

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...