由于工作需要,要根据现有的新闻数据统计词频,绘制词云图,比较擅长python,因此没有用可以生成云图的网页工具。由于我的数据量比较大,因此根据字符串自动进行统计并绘制云图的方式并不适合我。我需要手动从文件中读取数据并进行统计,然后将词频字典传入函数中进行绘制。

参考资料:

本文代码参考上述两个博客修改而成,语料为英文,因此未用到结巴分词,也不涉及字体问题。为适应mask,所以结果图比较简单,如需要调整参数的,可参考下面这篇文章,其中介绍了wordcloud的各种参数的含义。Wordcloud各参数含义

数据示例

{"date":"20130131","url":"http://gulftoday.ae/portal/5308f5d3-e752-41e0-b011-4537ffe658b2.aspx","locinfo":[["Uzbekistan","UZ","UZ","41","64"]],"content":"delivering advanced defence system agency deputy defence assaying trip increase influence soviet union political trade security initiative aim tighten cooperation attempt capability soviet security bloc collective security treaty organisation combine division surplus defence ministry quoted division rocket system sending division faced criticism lack activity inception signed treaty suspending membership bloc signed contract unit war torn military","label":["military diplomacy"]}

{"date":"20130128","url":"http://enews.fergananews.com/news.php?id=2795","locinfo":[["Fergana, Farg ona, Uzbekistan","UZ","UZ03","40.3933","71.7794"]],"content":"advocate pay rare political inmate initiative independent human advocate visited inmate convicted political motif penalty enforcement colony chairman permission obtained human advocate penalty enforcement directorate ministry internal affair hold academic degree technical science born lived chairman executive council member supreme council soviet republic appointed mayor arrested criminal conspiracy","label":["jail sentence"]}

结果

代码

#-*-coding:utf-8-*-

import sys

import os

from pprint import pprint

import codecs

import json

from collections import Counter, defaultdict

from wordcloud import WordCloud

import matplotlib.pyplot as plt

path = sys.path[0] + os.sep

def wc_from_text(str, fn):

'''根据字符串进行统计,并生成词云图'''

wc = WordCloud(

background_color="white", # 设置背景为白色,默认为黑色

width = 1500, # 设置图片的宽度

height= 960, # 设置图片的高度

margin= 10 # 设置图片的边缘

).generate(s)

plt.imshow(wc) # 绘制图片

plt.axis("off") # 消除坐标轴

plt.show() # 展示图片

wc.to_file(path + fn) # 保存图片

def wc_from_word_count(word_count, fp):

'''根据词频字典生成词云图'''

wc = WordCloud(

max_words=500, # 最多显示词数

# max_font_size=100, # 字体最大值

background_color="white", # 设置背景为白色,默认为黑色

width = 1500, # 设置图片的宽度

height= 960, # 设置图片的高度

margin= 10 # 设置图片的边缘

)

wc.generate_from_frequencies(word_count) # 从字典生成词云

plt.imshow(wc) # 显示词云

plt.axis('off') # 关闭坐标轴

plt.show() # 显示图像

wc.to_file(fp) # 保存图片

def generate_dict_from_file(fp):

with codecs.open(fp, 'r', 'utf-8') as source_file:

for line in source_file:

dic = json.loads(line)

yield dic

def main(data_fp, pic_fp):

word_count = defaultdict(lambda: 0)

for dic in generate_dict_from_file(data_fp):

words = dic['content'].split(' ')

for word in words:

word_count[word] += 1

with codecs.open(path + 'word_count.json', 'w', 'utf-8') as f:

json.dump(word_count, f, ensure_ascii=False)

wc_from_word_count(word_count, pic_fp)

if __name__ == '__main__':

s = 'access restored ban remains blocked government order accessible aid proxy provider telecom restored access celebrating government revoked censorship order newsroom waiting appeal court lawsuit government allowed constitution reporting stringer spread dedication journalism critical reporting brought outlet respect recognition landed blacklist authoritarian regime dominate permanently blocked severe intolerance critical journalism authority deny domestic access occasional basis regional outlet sensitive issue incident hard technical glitch deliberately blocked access depending covered government corruption human abuse social discontent policy freedom protested blocked violent conflict ethnic resident authority imposed permanent ban parliament resolution lawmaker addressed conflict recommended action government resolution reason obtaining court order law shutting outlet introduce measure domain space resolution authority'

# wc_from_text(s, 'wc1.jpg')

# word_count = Counter(s.split(' '))

# wc_from_word_count(word_count, 'wc2.jpg')

data_fp = path + 'result.json'

pic_fp = path + 'word_cloud_uz.jpg'

main(data_fp, pic_fp)

以上,欢迎交流。

python画字符形状的词云图_python根据词频字典或字符串绘制词云图相关推荐

  1. 根据词频、背景图绘制词云图

    根据词频.背景图绘制词云图 记录一下绘制词云图的过程 首先说明一下,绘制词云图完整的过程应如下: 获取一段文本,也就是要根据这个文本来绘制词云图 制作停用词词典,简单来说,停用词就是分词的规则,例如, ...

  2. 如何用python画金字塔形状_用 Python 画一只福鼠

    今年这个鼠年,尽管只是刚过了一个开头,但现实仿佛把我们很多年才需要经历的不好的事情,都在一瞬间抛向了我们,这个鼠年好像缺了点福气,本节我们使用 Python 画一只福鼠,为大家增添点福气,我们需要用到 ...

  3. python画半圆的指令是什么_python画圆的方式是什么

    python画圆的方式是什么 发布时间:2020-09-03 11:04:03 来源:亿速云 阅读:72 作者:小新 python画圆的方式是什么?这个问题可能是我们日常学习或工作经常见到的.希望通过 ...

  4. python画字符图片

    突然间对python用字符去画图产生了兴趣,就找到了下面这段别人的代码,通过理解,写上了自己的注释,做一下记录. from PIL import Image #从PIL模块导入Image类 impor ...

  5. 如何用python画金字塔形状_用Python画小猪佩奇,落叶树和动漫人物

    本文目录:小猪佩奇-落叶树-魔法少女 本文作者:小赖同学 ​ 最近在浏览Python文章时,无意中发现了一个好玩的画图工具turtle,看到各路大神竟然用Python画了一个图片出来,无法用言语来形容 ...

  6. python画出roc曲线 auc计算逻辑_Python画ROC曲线和AUC值计算

    前言 ROC(Receiver Operating Characteristic)曲线和AUC常被用来评价一个二值分类器(binary classifier)的优劣.这篇文章将先简单的介绍ROC和AU ...

  7. Python基础(四)(列表、元组、字典、字符串、Python内置函数、切片、运算符、成员运算符)

    高级变量类型 知识点回顾 Python 中数据类型可以分为 数字型 和 非数字型 数字型 整型 (int) 浮点型(float) 布尔型(bool) 真 True 非 0 数 -- 非零即真 假 Fa ...

  8. python画柱状图怎么规定x轴_Python:Matplotlib 画曲线和柱状图(Code)

    有少量修改,如有疑问,请访问原作者! 首先补充一下:两种体系7种颜色 r g b y m c k (红,绿,蓝,黄,品红,青,黑) 在科研的过程中,坐标系中的XY不一定就是等尺度的.例如在声波中对Y轴 ...

  9. python画圆并填充图形颜色_python turtle我想用五种颜色画五个圆,并且用画圆周的颜色填充,老是出问题,怎么回事,怎么修改?:python颜色代码...

    python看什么书 你想这看什么书的话,你可以看一下您的导师能力,有什么推荐的,或者职务上面问一下大神的呢? python turtle我想用五种颜色画五个圆,并且用画圆周的颜色填充,老是出问题,怎 ...

最新文章

  1. android将矩阵转换成字节数组,android-使用OpenGL矩阵转换将纹理从“ 1D”映...
  2. 【不屈】生如蝼蚁,当立鸿鹄之志
  3. 如何使用GitLab和Rancher构建CI/CD流水线–Part 1
  4. [转]李战大师-悟透delphi 第九章 多层体系结构
  5. windows下一些常用的dos命令
  6. 支持向量机的前世与今生
  7. python 流程控制基础知识总结 和九九乘法表、质数、水仙花数、猜拳游戏练习
  8. Android 存储学习之SQLite数据库的基本操作 (使用API操作数据库)
  9. 从 HTML 提取文本的 7 个工具
  10. CUDA编程入门极简教程
  11. 关于自抗扰控制的稳定性分析
  12. Error: While importing ‘run_app_dev‘, an ImportError was raised.
  13. Codeforces869 E. The Untended Antiquity (随机化算法)
  14. 201226元件_看电阻型号
  15. Excel查找匹配VLOOKUP用法
  16. 遇到oracle错误12514,【ORACLE】提示ORA-12514错误处理
  17. 2)react-redux抽离redux
  18. 网页版JS游戏五子棋单机版也可以改版成网络版
  19. 《金蝶ERP—K/3标准财务模拟实训(11.X版)》——导读
  20. mapbox 使用antv/l7添加下雨效果

热门文章

  1. 计算机软件硬件系统,计算机硬件系统和软件系统
  2. Java的新项目学成在线笔记-day9(十二)
  3. 郭德刚相声:德云社十周年的视频全集 下载 在线观看
  4. 计算机系统如何重置,电脑怎么重置系统电脑重置系统方法
  5. 腾讯应用宝app迁移,验证签名
  6. 响应式设计与自适应设计
  7. FFMPEG实现带NAT特性IPTV的播放
  8. 学计算机安徽有什么好大学,合肥工业大学,安徽大学,哪个学校计算机研究生比较好...
  9. 二,ESP8266 GPIO和SPI和定时器和串口
  10. 北京大学计算机系孙小虎,孙小虎-北京大学物理学院技术物理系