一个完整的大作业

 

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()

结果生成词云如图

 

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

转载于:https://www.cnblogs.com/hzlhzl/p/7761766.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值