【中国大学MOOC】北京理工大学 python程序与设计课程
jieba
参数 | 描述 | 例子 |
---|---|---|
jieba.lcut(s) | 精确模式,返回一个列表类型的分词结果 | >>> jieba.lcut("中国是一个伟大的国家") [‘中国’, ‘是’, ‘一个’, ‘伟大’, ‘的’, ‘国家’] |
jieba.lcut(s,cut_all=true) | 全模式,返回一个列表类型的分词结果,存在冗余 | >>> jieba.lcut("中国是一个伟大的国家",cut_all=True) [‘中国’, ‘国是’, ‘一个’, ‘伟大’, ‘的’, ‘国家’] |
jieba.lcut_for_search(s) | 搜索引擎模式,返回一个列表类型的分词结果,存在冗余 | >>> jieba.lcut_for_search("中华人民共和国是一个伟大的国家!") [‘中华’, ‘华人’, ‘人民’, ‘共和’, ‘共和国’, ‘中华人民共和国’, ‘是’, ‘一个’, ‘伟大’, ‘的’, ‘国家’, ‘!’] |
jieba.add_word(w) | 向分词词典增加新词w | >>> jieba.add_word("蟒蛇语言") |
- 英文文本:Hamet 分析词频
https://python123.io/resources/pye/hamlet.txt
#CalHamletV1.py
def getText():
txt = open(r"C:\Users\lenovo\Desktop\hamlet.txt","r").read() #文件路径前不加r报错
txt = txt.lower() #把所有的英文字符变成小写
for ch in '!#$%^&*()_"+./<>=;:,-~`?@[]{}\\|':
txt = txt.replace(ch," ")
return txt
hamletTxt = getText() #对文件进行读取和归一化
words = hamletTxt.split() #默认用空格分隔,存放在一个列表
counts = {} #定义一个字典
for word in words:
counts[word] = counts.get(word,0) + 1 #get方法获得某一个键对应的值
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))
- 中文文本:《三国演义》 分析人物
https://python123.io/resources/pye/threekingdoms.txt
import jieba
txt = open(r"C:\Users\lenovo\Desktop\三国演义.txt","r",encoding="gb18030").read()
excludes = {"将军","却说","荆州","二人","不可","不能","如此","左右"}
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "诸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "关公" or word == "云长":
rword == "关羽"
elif word == "玄德" or word == "玄德曰":
rword == "刘备"
elif word == "孟德" or word == "丞相":
rword == "曹操"
else:
rword = word
counts[rword] = counts.get(rword,0) + 1
for word in excludes:
del counts[word]
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))
wordcloud
w = wordcloud.WordCloud()
方法 | 描述 | 例子 |
---|---|---|
w.generate(txt) | 向wordcloud对象w中加载文本txt | >>>w.generate("Python and WordCloud") |
w.to_file(filename) | 将词云输出为图像文件,.png或.jpg格式 | >>>w.to_file("outfile.png") |
import wordcloud
w = wordcloud.WordCloud() #配置对象参数
w.generate("wordcloud by Python") #加载词云文本
w.to_file("pywordcloud.png") #输出词云文件
wordcloud库做的事情:
- 分隔:以空格分隔单词
- 统计:单词出现的次数并过滤
- 字体:根据统计配置字号
- 布局:颜色环境尺寸
w = wordcloud.WordCloud(<参数>)
参数 | 描述 | 例子 |
---|---|---|
width | 指定词云对象生成图片的宽度,默认400像素 | >>>w=wordcloud.WordCloud(width=600) |
height | 指定词云对象生成图片的高度,默认200像素 | >>>w=wordcloud.WordCloud(height=400) |
min_font_size | 指定词云中字体的最小字号,默认4号 | >>>w=wordcloud.WordCloud(min_font_size=10) |
max_font_size | 指定词云中字体的最大字号,根据高度自动调节 | >>>w=wordcloud.WordCloud(max_font_size=20) |
font_step | 指定词云中字体字号的步进间隔,默认为1 | >>>w=wordcloud.WordCloud(font_step=2) |
font_path | 指定文件字体的路径,默认None | >>>w=wordcloud.WordCloud(font_path="msyh.ttc") |
max_words | 指定词云显示的最大单词数量,默认200 | >>>w=wordcloud.WordCloud(font_step=2) |
stop_words | 指定词云的排除词列表,即不显示的单词列表 | >>>w=wordcloud.WordCloud(stop_words={"Python"}) |
mask | 指定词云形状,默认为长方形,需要应用imread()函数 | >>>from scipy.misc import imread >>>mk=imread("pic.png") >>>w=wordcloud.WordCloud(mask=mk) |
background_color | 指定词云图片的背景颜色,默认为黑色 | >>>w=wordcloud.WordCloud(background_color="white") |
- 英文(以空格分隔单词)
import wordcloud
txt = "life is short, you need python"
w = wordcloud.WordCloud(background_color = "white")
w.generate(txt)
w.to_file("pywcloud.png")
- 中文(中文需要先分词并组成空格分隔字符串)
import jieba
import wordcloud
txt = "程序设计语言是计算机能够理解和识别用户操作意图的一种交互体系,它按照特定规则组织计算机指令,使计算机能够自动进行各种运算处理。 "
w = wordcloud.WordCloud( width=1000,\
font_path="msyh.ttc",height=700)
w.generate(" ".join(jieba.lcut(txt)))
w.to_file("pywcloud.png")
jieba、wordcloud
推荐一个词云网站:易词云
import jieba
import wordcloud
from scipy.misc import imread
mask = imread("chinamap.png")
f = open("新时代中国特色社会主义.txt", "r", encodint="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud( font_path = "msyh.ttc", mask = mask,width = 1000, height = 700, background_color="white")
w.generate(txt)
w.to_file("wordcloud.png")
出现的问题:
-
OSError: cannot open resource
这个是字体问题。查了下我电脑的微软雅黑字体,名字为MSYH.ttc
-
ImportError: cannot import name ‘imread’ from 'scipy.misc’
imread依赖于pillow
把from scipy.misc import imread
改为from matplotlib.pyplot import imread
解决方法 -
UserWarning: mask image should be unsigned byte between 0 and 255. Got a float array
所用的图片是 png 且图片有透明区域
把格式改成 jpg 或把 png空白元素填充