python txt转换为字典,并用中文导出

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- encoding: gbk -*-
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import json
_dict = {}
def load_dict_from_file(filepath):

 try:
        with open("top64.txt", 'r') as dict_file:
            for line in dict_file:
                (key, value) = line.strip().split(':')
                _dict[key] = value
 except IOError as ioerr:
        print "文件 %s 不存在" % (filepath)
 return _dict
 my_wordcloud = WordCloud(
        background_color='black',  # 设置背景颜色 # 设置背景图片
        width=1000,
        height=800,
        max_words=200,  # 设置最大现实的字数l
        font_path="simsun.ttf",
        max_font_size=150,  # 设置字体最大值
        random_state=50,  # 设置有多少种随机生成状态,即有多少种配色方案
        scale=.5
    ).generate_from_frequencies(_dict)
 plt.imshow(my_wordcloud, interpolation='bilinear')
 plt.axis("off")
if __name__ == '__main__':
    _dict = load_dict_from_file ('dict.txt')
    print(json.dumps(_dict).decode("unicode-escape"))

plt.show()

通过代码成功将txt数据转换为了字典,并能够用中文打出。问题太多,慢慢来

没有画出来词云,可以借助网站https://worditout.com/word-cloud/create

猜你喜欢

转载自blog.csdn.net/zhangmary/article/details/80420118
今日推荐