# _*_ coding:utf-8 _*_
import requests
import threading
from bs4 import BeautifulSoup
import re
import os
import time
req_header={
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Cookie': 'UM_distinctid=162f5f44f0113-0313b684ffd29e-5e4c2719-100200-162f5f44f05116; __jsluid=d26199ff490223142ead3dca3b417f0d; PHPSESSID=rcqhhvqkvd9ggs9mqarotu54n7; CNZZDATA1272873895=1502087634-1524539933-null%7C1524545333',
'Host': 'm.biquge.com.tw',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.10 Mobile Safari/537.36',
}
req_url_base='http://m.biquge.com.tw/' #小說主地址
req_url=req_url_base+"wapbook/2016.html" #單獨一本小說地址
txt_section=req_url_base+"wapbook/"+'2016_1196115.html' #某一章頁面地址
# 請求當前章節頁面 params為請求參數
r=requests.get(str(txt_section),params=req_header)
# #soup轉換
soup=BeautifulSoup(r.text,"html.parser")
# #獲取章節名稱
# print(soup)
section_name=soup.select('#novelbody .content_title h1')[0].text
# print(section_name)
# #獲取章節文本
section_text=soup.select('#novelbody .content_novel #novelcontent p' )[0].text
# for ss in section_text.select("script"): #刪除無用項
# ss.decompose()
# #按照指定格式替換章節內容,運用正則表達式
section_text=re.sub( '\s+', '\r\n\t', section_text).strip('\r\n')
# print(section_text)
# print('章節名:'+section_name)
# print("章節內容:\n"+section_text)
from wordcloud import WordCloud
fo = open('1.txt', "ab+") #打開小說文件
# 以二進制寫入章節題目 需要轉換為utf-8編碼,否則會出現亂碼
fo.write(('\r' + section_name + '\r\n').encode('UTF-8'))
# 以二進制寫入章節內容
fo.write((section_text).encode('UTF-8'))
fo.close() #關閉小說文件
f = open('1.txt','r',encoding="UTF-8").read()
wordcloud = WordCloud(font_path='./fonts/simhei.ttf',background_color="white",width=1000, height=860, margin=2).generate(f)
# width,height,margin可以設置圖片屬性
# generate 可以對全部文本進行自動分詞,但是他對中文支持不好,對中文的分詞處理請看我的下一篇文章
#wordcloud = WordCloud(font_path = r'D:\Fonts\simkai.ttf').generate(f)
# 你可以通過font_path參數來設置字體集
#background_color參數為設置背景顏色,默認顏色為黑色
import matplotlib.pyplot as plt
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordcloud.to_file('test.png')
# 保存圖片,但是在第三模塊的例子中 圖片大小將會按照 mask 保存

這次的作業還是有難度的,我花了挺多時間的,主要問題就是那個我最后生成的詞雲沒有中文,只是邊框,最后是通過網上查資料找出了問題所在——wordcloud不支持中文,最后添加了中文字體的路徑,就成功了!還要繼續努力喲!
