LDA模型应用:一眼看穿希拉里的邮件
我们拿到希拉里泄露的邮件,跑一把LDA,看看她平时都在聊什么。
首先,导入我们需要的一些库
In [1]:
import numpy as np
import pandas as pd import re
然后,把希婆的邮件读取进来。
这里我们用pandas。不熟悉pandas的朋友,可以用python标准库csv
In [2]:
df = pd.read_csv("../input/HillaryEmails.csv") # 原邮件数据中有很多Nan的值,直接扔了。 df = df[['Id','ExtractedBodyText']].dropna()
文本预处理:
上过我其他NLP课程的同学都知道,文本预处理这个东西,对NLP是很重要的。
我们这里,针对邮件内容,写一组正则表达式:
(不熟悉正则表达式的同学,直接百度关键词,可以看到一大张Regex规则表)
In [3]:
def clean_email_text(text):
text = text.replace('\n'," ") #新行,我们是不需要的 text = re.sub(r"-", " ", text) #把 "-" 的两个单词,分开。(比如:july-edu ==> july edu) text = re.sub(r"\d+/\d+/\d+", "", text) #日期,对主体模型没什么意义 text = re.sub(r"[0-2]?[0-9]:[0-6][0-9]", "", text) #时间,没意义 text = re.sub(r"[\w]+@[\.\w]+", "", text) #邮件地址,没意义 text = re.sub(r"/[a-zA-Z]*[:\//\]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i", "", text) #网址,没意义 pure_text = '' # 以防还有其他特殊字符(数字)等等,我们直接把他们loop一遍,过滤掉 for letter in text: # 只留下字母和空格 if letter.isalpha() or letter==' ': pure_text += letter # 再把那些去除特殊字符后落单的单词,直接排除。 # 我们就只剩下有意义的单词了。 text = ' '.join(word for word in pure_text.split() if len(word)>1) return text
好的,现在我们新建一个colum,并把我们的方法跑一遍:
In [4]:
docs = df['ExtractedBodyText'] docs = docs.apply(lambda s: clean_email_text(s))
好,来看看长相:
In [5]:
docs.head(1).values
Out[5]:
我们直接把所有的邮件内容拿出来。
In [6]:
doclist = docs.values
LDA模型构建:
好,我们用Gensim来做一次模型构建
首先,我们得把我们刚刚整出来的一大波文本数据
[[一条邮件字符串],[另一条邮件字符串], ...]
转化成Gensim认可的语料库形式:
[[一,条,邮件,在,这里],[第,二,条,邮件,在,这里],[今天,天气,肿么,样],...]
引入库:
In [7]:
from gensim import corpora, models, similarities import gensim
为了免去讲解安装NLTK等等的麻烦,我这里直接手写一下停止词列表:
这些词在不同语境中指代意义完全不同,但是在不同主题中的出现概率是几乎一致的。所以要去除,否则对模型的准确性有影响
In [8]:
stoplist = ['very', 'ourselves', 'am', 'doesn', 'through', 'me', 'against', 'up', 'just', 'her', 'ours', 'couldn', 'because', 'is', 'isn', 'it', 'only', 'in', 'such', 'too', 'mustn', 'under', 'their', 'if', 'to', 'my', 'himself', 'after', 'why', 'while', 'can', 'each', 'itself', 'his', 'all', 'once', 'herself', 'more', 'our', 'they', 'hasn', 'on', 'ma', 'them', 'its', 'where', 'did', 'll', 'you', 'didn', 'nor', 'as', 'now', 'before', 'those', 'yours', 'from', 'who', 'was', 'm', 'been', 'will', 'into', 'same', 'how', 'some', 'of', 'out', 'with', 's', 'being', 't', 'mightn', 'she', 'again', 'be', 'by', 'shan', 'have', 'yourselves', 'needn', 'and', 'are', 'o', 'these', 'further', 'most', 'yourself', 'having', 'aren', 'here', 'he', 'were', 'but', 'this', 'myself', 'own', 'we', 'so', 'i', 'does', 'both', 'when', 'between', 'd', 'had', 'the', 'y', 'has', 'down', 'off', 'than', 'haven', 'whom', 'wouldn', 'should', 've', 'over', 'themselves', 'few',