将QQ聊天记录创建为词云

1. 导出并清洗qq聊天记录

  • 将qq聊天记录从电脑版qq导出

  • 去掉聊天中的图片表情以及时间戳

    具体代码如下:

    def Pretreatment():
        with open("未处理的聊天记录文件路径","r") as readfile:
            with open("处理后的聊天记录文件路径","at") as writefile:
    
                while True:
                    line = readfile.readline()
                    if line is '':
                        break
                    else:
                        line = readfile.readline().replace("[表情]","").replace("[图片]","")
                        writefile.write(str(line))
                        line = readfile.readline()
                print("ok")

2. 准备其他素材

  • 准备要生成图云的照片
  • 准备生成词云的字体(没有的话,会造成中文字体不显示的问题)

3. 准备使用到的python库

  • numpy : 处理图片文件
  • jieba : 聊天记录分词
  • matplotlib : 绘图
  • wordcloud : 绘制词云

4. 生成词云

text = open("../resource/new.txt","r").read()
    worldlist = jieba.cut(text,cut_all=False, HMM=True)
    wl = "/".join(worldlist)
    print(wl)

    coloring = np.array(Image.open("生成词云照片的路径"))
    wc = WordCloud(background_color="white", max_words=2000, mask=coloring,
                   max_font_size=50, random_state=42, font_path='字体文件的路径')
    wc.generate(wl)

    # create coloring from image
    image_colors = ImageColorGenerator(coloring)

    # show
    # 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    plt.show()
    wc.to_file("loveagin.png")

Reference

猜你喜欢

转载自www.cnblogs.com/freeyun/p/9502620.html
今日推荐