|
| 1 | +# -*- coding:utf-8 -*- |
| 2 | +import codecs |
| 3 | +import csv |
| 4 | +import re |
| 5 | + |
| 6 | +import jieba.analyse |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import requests |
| 9 | +from scipy.misc import imread |
| 10 | +from wordcloud import WordCloud |
| 11 | + |
| 12 | +__author__ = 'liuzhijun' |
| 13 | + |
| 14 | +cookies = { |
| 15 | + "ALF": "xxxx", |
| 16 | + "SCF": "xxxxxx.", |
| 17 | + "SUBP": "xxxxx", |
| 18 | + "SUB": "xxxx", |
| 19 | + "SUHB": "xxx-", "xx": "xx", "_T_WM": "xxx", |
| 20 | + "gsScrollPos": "", "H5_INDEX": "0_my", "H5_INDEX_TITLE": "xxx", |
| 21 | + "M_WEIBOCN_PARAMS": "xxxx" |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +def fetch_weibo(): |
| 26 | + api = "http://m.weibo.cn/index/my?format=cards&page=%s" |
| 27 | + for i in range(1, 102): |
| 28 | + response = requests.get(url=api % i, cookies=cookies) |
| 29 | + data = response.json()[0] |
| 30 | + groups = data.get("card_group") or [] |
| 31 | + for group in groups: |
| 32 | + text = group.get("mblog").get("text") |
| 33 | + text = text.encode("utf-8") |
| 34 | + |
| 35 | + def cleanring(content): |
| 36 | + """ |
| 37 | + 去掉无用字符 |
| 38 | + """ |
| 39 | + pattern = "<a .*?/a>|<i .*?/i>|转发微博|//:|Repost|,|?|。|、|分享图片" |
| 40 | + content = re.sub(pattern, "", content) |
| 41 | + return content |
| 42 | + |
| 43 | + text = cleanring(text).strip() |
| 44 | + if text: |
| 45 | + yield text |
| 46 | + |
| 47 | + |
| 48 | +def write_csv(texts): |
| 49 | + with codecs.open('./weibo.csv', 'w') as f: |
| 50 | + writer = csv.DictWriter(f, fieldnames=["text"]) |
| 51 | + writer.writeheader() |
| 52 | + for text in texts: |
| 53 | + writer.writerow({"text": text}) |
| 54 | + |
| 55 | + |
| 56 | +def read_csv(): |
| 57 | + with codecs.open('./weibo.csv', 'r') as f: |
| 58 | + reader = csv.DictReader(f) |
| 59 | + for row in reader: |
| 60 | + yield row['text'] |
| 61 | + |
| 62 | + |
| 63 | +def word_segment(texts): |
| 64 | + jieba.analyse.set_stop_words("./stopwords.txt") |
| 65 | + for text in texts: |
| 66 | + tags = jieba.analyse.extract_tags(text, topK=20) |
| 67 | + yield " ".join(tags) |
| 68 | + |
| 69 | + |
| 70 | +def generate_img(texts): |
| 71 | + data = " ".join(text for text in texts) |
| 72 | + |
| 73 | + mask_img = imread('./heart-mask.jpg', flatten=True) |
| 74 | + wordcloud = WordCloud( |
| 75 | + font_path='msyh.ttc', |
| 76 | + background_color='white', |
| 77 | + mask=mask_img |
| 78 | + ).generate(data) |
| 79 | + plt.imshow(wordcloud) |
| 80 | + plt.axis('off') |
| 81 | + plt.savefig('./heart.jpg', dpi=600) |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == '__main__': |
| 85 | + texts = fetch_weibo() |
| 86 | + write_csv(texts) |
| 87 | + generate_img(word_segment(read_csv())) |
0 commit comments