補交作業
- 詞頻統計預處理
- 下載一首英文的歌詞或文章
- 將所有,.?!’:等分隔符全部替換為空格
- 將所有大寫轉換為小寫
- 生成單詞列表
- 生成詞頻統計
- 排序
- 排除語法型詞匯,代詞、冠詞、連詞
- 輸出詞頻最大TOP10
截圖:
中文詞頻統計
下載一長篇中文文章。
從文件讀取待分析文本。
news = open(‘gzccnews.txt‘,‘r‘,encoding = ‘utf-8‘)
安裝與使用jieba進行中文分詞。
pip install jieba
import jieba
list(jieba.lcut(news))
生成詞頻統計
排序
排除語法型詞匯,代詞、冠詞、連詞
輸出詞頻最大TOP20
按 Ctrl+C 復制代碼 按 Ctrl+C 復制代碼
網絡爬蟲基礎練習
0.可以新建一個用於練習的html文件,在瀏覽器中打開。
1.利用requests.get(url)獲取網頁頁面的html文件
import requests
newsurl=‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘
res = requests.get(newsurl) #返回response對象
res.encoding=‘utf-8‘
2.利用BeautifulSoup的HTML解析器,生成結構樹
from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text,‘html.parser‘)
3.找出特定標簽的html元素
soup.p #標簽名,返回第一個
soup.head
soup.p.name #字符串
soup.p. attrs #字典,標簽的所有屬性
soup.p. contents # 列表,所有子標簽
soup.p.text #字符串
soup.p.string
soup.select(‘li‘)
4.取得含有特定CSS屬性的元素
soup.select(‘#p1Node‘)
soup.select(‘.news-list-title‘)
5.練習:
取出h1標簽的文本
取出a標簽的鏈接
取出所有li標簽的所有內容
取出第2個li標簽的a標簽的第3個div標簽的屬性
取出一條新聞的標題、鏈接、發布時間、來源
# -*- coding : UTF-8 -*- # -*- author : onexiaofeng -*- import requests url=‘http://localhost:63342/hello/venv/lz.html?_ijt=l26l1kkfr4kkmba1tsi16auibm‘ res=requests.get(url) res.encoding=‘utf-8‘ res.text from bs4 import BeautifulSoup soup=BeautifulSoup(res.text,‘html.parser‘) soup print(soup.h1.text) print(soup.a[‘href‘]) for i in soup.select(‘li‘): print(i) print(soup.select(‘li‘)[1].a.select(‘div‘)[2].attrs) print(‘標題:‘+soup.select(‘.news-list-title‘)[0].text) print(‘鏈接:‘+soup.select(‘a‘)[2][‘href‘]) print(‘發布時間:‘+soup.select(‘.news-list-info‘)[0].span.text) print(‘來源:‘+soup.select(‘.news-list-info‘)[0].select(‘span‘)[1].text)
截圖:
1.取出一個新聞列表頁的全部新聞 包裝成函數。
2.獲取總的新聞篇數,算出新聞總頁數。
3.獲取全部新聞列表頁的全部新聞詳情。
import requests from bs4 import BeautifulSoup from datetime import datetime import re #獲得新聞點擊次數 def getclick(link): newId = re.search(‘\_(.*).html‘, link).group(1).split(‘/‘)[1] click = requests.get(‘http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80‘.format(newId)) return click.text.split(‘.html‘)[-1].lstrip("(‘").rstrip("‘);") def getnewsdetail(link): resd = requests.get(link) resd.encoding = ‘utf-8‘ soupd = BeautifulSoup(resd.text, ‘html.parser‘) content=soupd.select(‘.show-content‘)[0].text info=soupd.select(‘.show-info‘)[0].text clickcount = getclick(link) time=re.search(‘(\d{4}.\d{2}.\d{2}\s\d{2}.\d{2}.\d{2})‘,info).group(1) if (info.find(‘作者‘) > 0): author = re.search(‘作者:((.{2,4}\s|.{2,4}、|.{2,4},|\w*\s){1,5})‘, info).group(1) else: author = ‘none‘ if (info.find(‘審核‘) > 0): auditing = re.search(‘審核:((.{2,4}\s|.{2,4}、|.{2,4},|\w*\s){1,5})‘, info).group(1) else: auditingr = ‘none‘ if (info.find(‘來源:‘) > 0): source = re.search(‘來源:(.*)\s*攝|點‘, info).group(1) else: source = ‘none‘ dateTime=datetime.strptime(time,‘%Y-%m-%d %H:%M:%S‘) print(‘發布時間:{0}\n作者:{1}\n審核:{2}\n來源:{3}\n點擊次數:{4}‘.format(dateTime,author,auditing,source,clickcount)) print(content) def getlistpage(listlink): res=requests.get(listlink) res.encoding=‘utf-8‘ soup=BeautifulSoup(res.text,‘html.parser‘) for news in soup.select(‘li‘): if (len(news.select(‘.news-list-title‘)) > 0): title = news.select(‘.news-list-title‘)[0].text description = news.select(‘.news-list-description‘)[0].text link = news.a.attrs[‘href‘] print(‘新聞標題:{0}\n新聞描述:{1}\n新聞鏈接:{2}‘.format(title,description,link)) getnewsdetail(link) break listlink=‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘ from datetime import datetime getlistpage(listlink) res=requests.get(listlink) res.encoding=‘utf-8‘ soup=BeautifulSoup(res.text,‘html.parser‘) listCount = int(soup.select(‘.a1‘)[0].text.rstrip(‘條‘))//10+1 for i in range(2,listCount): listlink=‘http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html‘.format(i) getlistpage(listlink)
4.找一個自己感興趣的主題,進行數據爬取,並進行分詞分析。不能與其它同學雷同。
# -*- coding: UTF-8 -*- # -*- author: yjw -*- import requests import re import jieba from bs4 import BeautifulSoup from datetime import datetime def getnewdetail(link): res=requests.get(link) res.encoding=‘gb2312‘ soup=BeautifulSoup(res.text,‘html.parser‘) Alltext=len(soup.select(".text")) content=‘‘ for p in range(0,Alltext): content+=soup.select(‘.text‘)[p].text+‘\n‘ if(Alltext>0): print(content+"\n詞頻統計:") delword={[‘我‘, ‘他‘, ‘你‘, ‘了‘, ‘那‘, ‘又‘, ‘-‘, ‘的‘, ‘我們‘, ‘是‘, ‘但‘, ‘中‘, ‘這‘, ‘在‘, ‘也‘, ‘都‘, ‘而‘,‘你‘,‘ ‘,‘我‘,‘我們‘, ‘他‘, ‘他們‘, ‘我的‘, ‘他的‘, ‘你的‘, ‘呀‘, ‘和‘, ‘是‘,‘,‘,‘。‘,‘:‘,‘“‘,‘”‘,‘的‘,‘啊‘,‘?‘,‘在‘,‘了‘, ‘說‘,‘去‘,‘與‘,‘不‘,‘是‘,‘、‘,‘也‘,‘又‘,‘!‘,‘著‘,‘兒‘,‘這‘,‘到‘,‘就‘, ‘\n‘,‘(‘,‘)‘,‘那‘,‘有‘,‘上‘,‘便‘,‘和‘,‘只‘,‘要‘,‘小‘,‘罷‘,‘那裏‘, ‘…‘,‘一個‘,‘?‘,‘人‘,‘把‘,‘被‘,‘她‘,‘都‘,‘道‘,‘好‘,‘還‘,‘’‘,‘‘‘,‘呢‘,‘來‘,‘得‘,‘你們‘,‘才‘,‘們‘ ‘\n‘, ‘,‘, ‘。‘, ‘?‘, ‘!‘, ‘“‘, ‘”‘, ‘:‘, ‘;‘, ‘、‘, ‘.‘, ‘‘‘, ‘’‘, ‘(‘, ‘)‘, ‘ ‘, ‘【‘, ‘】‘, ‘…‘] } word={} newscontent=list(jieba.cut(content)) wordfit=set(newscontent)-set(delword) for i in wordfit: word[i]=newscontent.count(i) text = sorted(text3.items(), key=lambda x: x[1], reverse=True) for i in range(20): print(text[i]) else: print(‘picture‘) def getnewlist(link): res=requests.get(link) res.encoding=‘gb2312‘ soup=BeautifulSoup(res.text,‘html.parser‘) for newlist in soup.select(‘.listInfo‘)[0].select(‘li‘): title = newsList.select(‘a‘)[0].text time = newsList.select(‘.info‘)[0].select(‘p‘) link = newsList.select(‘a‘)[0][‘href‘] print(‘\n新聞標題:{0}\n發表時間:{1}\n新聞鏈接:{2}\n‘.format(title, time, link)) getnewdetail(link) link=‘http://sports.qq.com/a/20180411/020544.htm‘ getnewlist(link) for i in range(1,20): if(i==1): getnewlist(link) else: link="http://sports.qq.com/a/20180411/020544_{}.htm".format(i) getnewslist(link)
補交作業