一个完整的大作业

 

1.选一个自己感兴趣的主题。

2.网络上爬取相关的数据。

3.进行文本分析,生成词云。

4.对文本分析结果解释说明。

5.写一篇完整的博客,附上源代码、数据爬取及分析结果,形成一个可展示的成果。

首先选择百度贴吧猫的主题

 

爬取数据代码如下

url = "http://tieba.baidu.com/f?kw=%E7%8C%AB&ie=utf-8&pn="


def get_title(url):
    html = urlopen(url)
    bs = BeautifulSoup(html, "html.parser")
    for title in bs.find_all("a", attrs={"class": "j_th_tit"}):
        with open("text.txt", "a+") as f:
            f.write(title.get_text() + "\n")

for i in range(10):
    print("page:", i)
    l = url + str(i * 50)
    get_title(l)

爬取500条数据,每页50条标题,共10页

 

 

 爬取到数据之后就对数据进行分析和统计,代码如下

f = open("counts.txt", "a+")
text = open("text.txt", "r", encoding="utf-8").read()
ex = ["怎么", "什么", "这是"]
counts = {}

ls = []
words = jieba.lcut(text)
for word in words:
    ls.append(word)
    if len(word) == 1 or word in ex:
        continue
    counts[word] = counts.get(word, 0) + 1

items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(100):
    word, count = items[i]
    print("{:<10}{:>5}".format(word, count))
    f.write("{:<10}{:>5}".format(word, count) + "\n")
f.close()

 结果的部分如图

 

再对这些数据做成词云,代码如下

txt = " ".join(words)
my_wordcloud = wordcloud.WordCloud(font_path="/usr/share/font/simsun.ttf").generate(txt)

plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

结果生成词云如图

 

从中可以看到猫咪出现词语占多数 

posted @ 2017-10-31 15:28  47何梓亮  阅读(184)  评论(0编辑  收藏  举报