案例背景
当前,很多网站提供新闻列表,可以令用户方便的查阅自己感兴趣的信息。
然而,用户浏览新闻,也许仅仅只是随便看到一条。网站的资源非常丰富,可能收藏很多用户感兴趣的其他新闻,但是受限于用户对新闻了解的广泛度,很多新闻用户未能发现,网站也因此错误了很多吸引用户的机会。
可以根据用户浏览过的新闻,创建词云图,查看用户浏览的关键信息,进而可以根据浏览的新闻,与网站现有的其他新闻进行匹配,自动推断出用户最可能感兴趣的新闻,从而达到吸引顾客,防止顾客流失,增加网站流量等目的。
数据集描述
数据集采用搜狗2012年6月-7月全网新闻数据。该数据集为xml文件格式类型。格式如下:
<doc>
<url>新闻链接</url>
<docno>新闻编号</docno>
<contenttitle>新闻标题</contenttitle>
<content>新闻内容</content>
</doc>
导入相关的库
import numpy as np
import pandas as pd
import re
import jieba
import wordcloud
import scipy.misc
原始数据的处理
数据集是一个xml类型的文件,不能使用pandas直接进行加载。
先读取原始的数据集,使用正则表达式提取<contenttitle>
与</contenttitle>
中的标题信息,并将信息输出到另外一个文档中。
re_obj = re.compile(r"<contenttitle>(.+?)</contenttitle>")
re_obj2 = re.compile(r"<content>(.+?)</content>")
with open("news_tensite_xml.dat", encoding="ANSI") as f, open("news.dat", "wt", encoding="ANSI") as f2:
for line in f:
match = re_obj.match(line)
if match:
f2.write(match.group(1))
line2 = f.readline()
match2 = re_obj2.match(line2)
if match2:
f2.write(match2.group(1))
f2.write("\n")
加载数据,数据清洗
#加载数据集,查看数据的基本信息
news = pd.read_csv(r"news.dat", header=None, names=["content"], encoding="ANSI")
display(news.shape) #形状为(1293605, 1)
display(news.head())
#缺失值处理
news.isnull().sum() #结果为0,没有缺失值
#重复值处理
news.drop_duplicates(inplace=True)
display(news.shape) #由原本的(1293605, 1)变为(995364, 1)
去特殊字符,分词,去除停用词
# 特殊字符
re_obj = re.compile(r"[!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~——!,。?、¥…():【】《》‘’“”\s\ue40c]+")
# 获取停用词列表
def get_stopword():
with open('中文停用词整理.txt', 'r', encoding='utf-8') as f:
text = f.read()
textlist = text.split(';\n')
s = set(textlist)
return s
stopword = get_stopword()
# 清洗文本数据
def clear(text):
return re_obj.sub("", text)
# 进行分词的函数。
def cut_word(text):
return jieba.cut(text)
# 去掉停用词函数。
def remove_stopword(words):
return [word for word in words if word not in stopword]
# 过程函数
def preprocess(text):
text = clear(text)
word_iter = cut_word(text)
word_list = remove_stopword(word_iter)
return word_list
# 执行过程函数
news["content"] = news["content"].apply(preprocess)
词云图统计
wc = wordcloud.WordCloud(font_path=r"C:/Windows/Fonts/STFANGSO.ttf", mask=scipy.misc.imread("map.jpg"), background_color = 'white')
li = news_["content"].tolist()
li = list(chain.from_iterable(li))
join_words = " ".join(li)
img = wc.generate(join_words)
wc.to_file("wordcloud1.png")
指定中国地图作为背景,生成词云图。