第三方库的安装
在python有时候我们需借助第三方库进行操作, 安装方式常用
- pip 安装
pip install 库的名字
- pycharm界面安装
import jieba
from wordcloud import WordCloud
# 读取小说文件
def parse():
with open('threekingdom.txt', mode='r', encoding='utf-8') as f:
data = f.read()
print(type(data))
print(len(data))
# 词频统计 中文单词之间没有空格 , 借助中文分词工具
word_list = jieba.lcut(data)
print(len(word_list))
print(word_list)
text = " ".join(word_list)
wc = WordCloud(
font_path="MSYH.TTC",
background_color="white",
width=500,
height=500
)
wc.generate(text).to_file('三国演义词云.png')
# {"九日":1, "潼关":3....}
counts = {}
for word in word_list:
if len(word) <= 1:
continue
else:
counts[word] = counts.get(word, 0) + 1
print(counts)
parse()
词云
# pip install wordcloud
from wordcloud import WordCloud
text = "哈哈 哈哈 哈哈 哈哈 哈哈 i like python python is life python python python life life life life"
wc = WordCloud(
font_path="MSYH.TTC",
background_color="white",
width=500,
height=500
)
wc.generate(text).to_file('myciyun.png')
排序
# 简单排序
from random import randint
# ls = [randint(1, 100) for _ in range(10)]
# print(ls)
# new_ls = sorted(ls, reverse=True)
# print(new_ls)
# print(ls)
# 字典的排序
import string
score_info = {k: randint(40, 100) for k in string.ascii_uppercase[:7]}
print(score_info)
# 按照成绩进行排序
score_ls = list(score_info.items())
print(score_ls)
def sort_by_score(x):
return x[1]
# key指定排序的规则 按照什么标准进行排序
res_ls = sorted(score_ls, key=sort_by_score)
print(res_ls)