目录
爬虫
对于爬虫顾名思义就是爬的虫子,而对于网络上的爬虫的作用是爬取网页上的信息并且把它保存在用户的电脑中
我的爬虫是由python来实现的对于python来说原始的库并不能满足对于爬虫的实现
还需要添加一些额外的包比如
BeautifulSoup包以及re正则包urllib包
下边是添加的包
from bs4 import BeautifulSoup
import re
import urllib.request,urllib.error
想要爬取网站必须要先对于网页的源代码进行分析下边的程序就是对网页的链接和获取代码并且进行解析
ef askurl(url):
head = {#伪装
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.47"
}
request = urllib.request.Request(url,headers=head)
html = ""
try:
reponse = urllib.request.urlopen(request)
html = reponse.read().decode("gbk")
#print(html)
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
获取到网页源代码后就要对代码进行选择性的提取这就要用到正则表达式下边代码是对正则表达式的应用
findlink = re.compile(r'<a href="(http://[a-z]*.people.com.cn/n1.*?.html)" target=".*?">')
findtitle = re.compile(r'<h1>(.*?)</h1>')
findtext1 = re.compile(r'<p style="text-indent: 2em;">(.*?)</p>',re.S)
findtext2 = re.compile(r'<p>(.*?[^a-z])</p>')
finddiv = re.compile(r'<div class="(.*? cf)">')
在提取到想要的信息后就要对信息进行保存下边的程序是对信息的保存
date = []
datelist = []
for i in cesbs.find_all("div",class_="main"):
i = str(i)
#print(i)
title = re.findall(findtitle,i)
#print(title)
text = re.findall(findtext1,i)
if len(text)==0:
text = re.findall(findtext2,i)
date.extend(title)
date.extend(text)
#print(text)
f = open('人民日报.txt',"w",encoding='utf-8')
datelist.append(date)
#print(datelist)
date1 = datelist[0]
for i in date1:
f.write(i)
词云
1.1. 引入库
import jieba
import numpy as np
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
1.2.设置文件路径
fname_text ="人民日报.txt"
fname_stop = "hit_stopwords.txt"
fanme_font = 'FZSTK.TTF'
2. 文本处理
这一步的主要目的是将一篇文章转化为一个”词频”表 (字典 dict).
2.1 读取文本
text = open(fname_text,encoding = 'utf-8').read()
STOPWORDS_CH = open(fname_stop,encoding = 'utf-8').read().split()
word_list = [
w for w in jieba.cut(text)
if w not in set(STOPWORDS_CH) and len(w)>1
首先, 我们得读取一篇文章, 以及停用词表:
2.2 分词和过滤
def count_frequencies(word_List):
freq = dict()
for w in word_list:
if w not in freq.keys():
freq[w] = 1
else:
freq[w] += 1
return freq
首先用 jieba.cut(text) 函数将字符串 text 分割成一个个词或词组 (该函数返回的是一个’生成器 generator), 然后对里面的每一个词, 过滤掉没有意义的 ‘停用词’ (w not in STOPWORDS_CH), 最后只保留长度大于1的词组 (len(w) > 1).
2.3 统计词频:
freq = count_frequencies(word_list)
wcd = WordCloud(font_path=fanme_font)
wcd.generate_from_frequencies(freq)
下面代码定义了一个函数, 输入一个词语列表, 输出保存每个词语出现频率的字典.
当然也可以利用 colections.Counter() 或 pandas.value_count() 函数来计算, 以下代码与上面等价:
3.1 默认颜色
def plt_imshow(x,ax = None,show = True):
if ax is None:
fig,ax = plt.subplots()
ax.imshow(x)
ax.axis("off")
if show:plt.show()
return ax
plt_imshow(wcd)
首先用 WordCloud() 建立一个词云的对象, 并设置好初始参数 (字体的路径). 然后基于刚刚建立的词频生成词云.