网页图片获取与词频统计词云生成

  • 网页图片获取

代码如下:

import requests
import os
url='https://xxxx/xx.jpg'
root='E://下载//'
path=root+split('/')[-1]
print(path)
try:
     if not os.path.exists(root):
          os.mkdir(root)
     if not os.path.exists(path):
          r=requests.get(url)
          with open(path,'wb') as f:
               f.write(r.content)
               f.close()
               print('success')
     else:
​
          print('exists')
except:
     print('fail')
  • 词频统计与词云生成

英文词云词频代码如下:

# Prince.py
import wordcloud
​
​
def getText():
    txt = open("princess.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")
    return txt
​
​
princess = getText()
words = princess.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))
​
w = wordcloud.WordCloud(width=1000, height=700,
                        background_color="pink")
w.generate(getText())
w.to_file("x.png")

效果如下:

 

中文词云词频代码如下:

import jieba
import wordcloud
​
txt = open("CN_prince.txt", "r", encoding="utf-8").read()
excludes = {"这种", "非常", "可是", "如果", "了解", "这是",
            "因此", "为什么", "它们", "这个", "一棵", "一个", "他们"}
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word, 0) + 1
for word in excludes:
    del counts[word]
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
​
w = wordcloud.WordCloud(width=1000, height=700, font_path='msyh.ttc',
                        background_color="pink")
for i in range(10):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))
​
​
def getText():
    s = str(words)
    for ch in "'n我的是就有它们这种":
        s = s.replace(ch, " ")
    return s
​
​
w.generate(getText())
w.to_file("y.png")

效果如下:

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值