这篇文章主要介绍了基于python3生成标签云代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
标签云是现在大数据里面最喜欢使用的一种展现方式,其中在python3下也能实现标签云的效果,贴图如下:
首先要安装以下几个库:
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-
# http://www.lfd.uci.edu/~gohlke/pythonlibs/#cx_freeze
# 万能仓库下载pygame
# pip3下载simplejson
还有最重要的库:
pip3 install pytagcloud
或者去官网下载:https://pypi.python.org/pypi/pytagcloud/
安装完毕,利用官网的例子来做:
from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts
YOUR_TEXT = "A tag cloud is a visual representation for text data, typically\
used to depict keyword metadata on websites, or to visualize free form text."
tags = make_tags(get_tag_counts(YOUR_TEXT), maxsize=120)
create_tag_image(tags, 'cloud_large.png', size=(900, 600), fontname='Lobster')
果断报错:
Traceback (most recent call last):
File "D:/code/pythonwork/Text.py", line 96, in <module>
tags = make_tags(get_tag_counts(YOUR_TEXT), maxsize=120)
File "C:\Python34\lib\site-packages\pytagcloud\lang\counter.py", line 25, in get_tag_counts
return sorted(counted.iteritems(), key=itemgetter(1), reverse=True)
AttributeError: 'dict' object has no attribute 'iteritems'
看了发现问题出在库中的:
# counter.py
return sorted(counted.iteritems(), key=itemgetter(1), reverse=True)
原来是python3.4不支持写法:
在Python2.x中,items( )用于 返回一个字典的拷贝列表【Returns a copy of the list of all items (key/value pairs) in D】,占额外的内存。
iteritems() 用于返回本身字典列表操作后的迭代【Returns an iterator on all items(key/value pairs) in D】,不占用额外的内存。
Python 3.x 里面,iteritems() 和 viewitems() 这两个方法都已经废除了,而 items() 得到的结果是和 2.x 里面 viewitems() 一致的。在3.x 里 用items()替换iterite