Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo Word Cloud bằng Python


Trong bài này, có file chứa văn bản. Ta phải tạo Word Cloud từ văn bản đó và một hình ảnh mask. Chương trình lưu ảnh word cloud dạng png.

Để triển khai, cần dùng các thư viện: matplotlib, wordcloud, numpy, tkinter và PIL.

Cài đặt thư viện

$ sudo pip3 install matplotlib
$ sudo pip3 install wordcloud
$ sudo apt-get install python3-tk

Sau khi cài đặt, viết mã Python để thực hiện.

Thuật toán

Bước 1: Đọc dữ liệu từ file lưu vào 'dataset'.
Bước 2: Tạo mảng pixel từ ảnh mask.
Bước 3: Tạo word cloud từ dataset. Thiết lập background color, mask, stop-words.
Bước 4: Lưu ảnh cuối ra disk.

Input: sampleWords.txt file

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

Input khác là ảnh mask (cloud.png). Kết quả cuối ở bên phải.

Tạo Word Cloud bằng Python

Ví dụ mã

import matplotlib.pyplot as pPlot
from wordcloud import WordCloud, STOPWORDS
import numpy as npy
from PIL import Image

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

def create_word_cloud(string):
    maskArray = npy.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)

Kết quả

Tạo Word Cloud bằng Python