NLP中的文本分析和特征工程( 二 )


txt = dtf["text"].iloc[0]print(txt, " --> ", langdetect.detect(txt))

NLP中的文本分析和特征工程

文章插图
 
让我们为整个数据集添加一列带有语言信息:
dtf['lang'] = dtf["text"].apply(lambda x: langdetect.detect(x) if x.strip() != "" else "")dtf.head()
NLP中的文本分析和特征工程

文章插图
 
dataframe现在有一个新列 。使用相同的代码从以前,我可以看到有多少不同的语言:
 
NLP中的文本分析和特征工程

文章插图
 
即使有不同的语言,英语也是主要的 。所以我打算用英语过滤新闻 。
dtf = dtf[dtf["lang"]=="en"]文本预处理数据预处理是准备原始数据使其适合于机器学习模型的阶段 。对于NLP,这包括文本清理、停止词删除、词干填塞和词元化 。
文本清理步骤根据数据类型和所需任务的不同而不同 。通常,字符串被转换为小写字母,并且在文本被标记之前删除标点符号 。标记化是将一个字符串分割成一个字符串列表(或“记号”)的过程 。
让我们以第一个新闻标题为例:
print("--- original ---")print(txt)print("--- cleaning ---") txt = re.sub(r'[^ws]', '', str(txt).lower().strip()) print(txt)print("--- tokenization ---") txt = txt.split() print(txt)
NLP中的文本分析和特征工程

文章插图
 
我们要保留列表中的所有标记吗?不需要 。实际上,我们希望删除所有不提供额外信息的单词 。在这个例子中,最重要的单词是“song”,因为它可以为任何分类模型指明正确的方向 。相比之下,像“and”、“for”、“the”这样的词没什么用,因为它们可能出现在数据集中的几乎每一个观察结果中 。这些是停止词的例子 。这个表达通常指的是一种语言中最常见的单词,但是并没有一个通用的停止词列表 。
我们可以使用NLTK(自然语言工具包)为英语词汇创建一个通用停止词列表,它是一套用于符号和统计自然语言处理的库和程序 。
lst_stopwords = nltk.corpus.stopwords.words("english")lst_stopwords
NLP中的文本分析和特征工程

文章插图
 
让我们删除第一个新闻标题中的停止词:
print("--- remove stopwords ---")txt = [word for word in txt if word not in lst_stopwords] print(txt) 
NLP中的文本分析和特征工程

文章插图
 
我们需要非常小心停止词,因为如果您删除错误的标记,您可能会丢失重要的信息 。例如,“will”这个词被删除,我们丢失了这个人是will Smith的信息 。记住这一点,在删除停止词之前对原始文本进行一些手工修改可能会很有用(例如,将“Will Smith”替换为“Will_Smith”) 。
既然我们有了所有有用的标记,我们就可以应用单词转换了 。词根化和词元化都产生单词的词根形式 。区别在于stem可能不是一个实际的单词,而lemma是一个实际的语言单词(词干词干通常更快) 。这些算法都由NLTK提供 。
print("--- stemming ---")ps = nltk.stem.porter.PorterStemmer() print([ps.stem(word) for word in txt])print("--- lemmatisation ---") lem = nltk.stem.wordnet.WordNetLemmatizer() print([lem.lemmatize(word) for word in txt])
NLP中的文本分析和特征工程

文章插图
 
正如您所看到的,一些单词发生了变化:“joins”变成了它的根形式“join”,就像“cups”一样 。另一方面,“official”只是在词干“offici”中发生了变化,而“offici”不是一个单词,它是通过删除后缀“-al”而创建的 。
我将把所有这些预处理步骤放入一个函数中,并将其应用于整个数据集 。
'''Preprocess a string. :parameter     :param text: string - name of column containing text     :param lst_stopwords: list - list of stopwords to remove     :param flg_stemm: bool - whether stemming is to be applied     :param flg_lemm: bool - whether lemmitisation is to be applied :return     cleaned text ''' def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None):     ## clean (convert to lowercase and remove punctuations and characters and then strip)     text = re.sub(r'[^ws]', '', str(text).lower().strip())                  ## Tokenize (convert from string to list)     lst_text = text.split()    ## remove Stopwords     if lst_stopwords is not None:         lst_text = [word for word in lst_text if word not in                      lst_stopwords]                      ## Stemming (remove -ing, -ly, ...)     if flg_stemm == True:         ps = nltk.stem.porter.PorterStemmer()         lst_text = [ps.stem(word) for word in lst_text]                      ## Lemmatisation (convert the word into root word)     if flg_lemm == True:         lem = nltk.stem.wordnet.WordNetLemmatizer()         lst_text = [lem.lemmatize(word) for word in lst_text]                  ## back to string from list     text = " ".join(lst_text)     return text


推荐阅读