Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สร้าง Word Cloud ด้วย Python


สร้าง Word Cloud จากไฟล์ข้อความและรูปภาพ mask ใช้ libraries: matplotlib, wordcloud, numpy, tkinter, PIL

ติดตั้งไลบรารี

pip3 install matplotlib wordcloud
apt-get install python3-tk

อัลกอริทึม

  1. อ่านข้อความจากไฟล์
  2. สร้าง pixel array จาก mask image
  3. สร้าง WordCloud object ตั้งค่า background, mask, stopwords
  4. generate จากข้อความ และ save เป็น PNG

โค้ดตัวอย่าง

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import numpy as np
from PIL import Image

dataset = open("sampleWords.txt", "r").read()

def create_word_cloud(string):
    maskArray = np.array(Image.open("cloud.png"))
    cloud = WordCloud(background_color="white", max_words=200, mask=maskArray, stopwords=set(STOPWORDS))
    cloud.generate(string)
    cloud.to_file("wordCloud.png")

dataset = dataset.lower()
create_word_cloud(dataset)

ผลลัพธ์

ได้ไฟล์ wordCloud.png เป็นรูปภาพ word cloud ตามรูป mask