찾다
백엔드 개발파이썬 튜토리얼Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

python을 기반으로 생성된 워드클라우드

워드클라우드는 지난 2년간 뜨거운 화제가 되었습니다. 이 글을 10분만 투자하여 읽어보시면 아마 아시는 분들은 더 이상 부럽지 않으실 것입니다. 단어 구름을 사용하는 방법. 그것은 로켓 과학이 아닙니다. 당신도 배울 수 있습니다. 와서 시도해 보세요!

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

이 기사에서는 영어 단어 구름 만드는 방법을 설명합니다. 다음 호에서는 중국어 단어 구름 만드는 방법을 보여드릴 테니 계속 지켜봐주세요!

빠른 워드 클라우드 생성

from wordcloud import WordCloud
f = open(u'txt/AliceEN.txt','r').read()
wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(f)
# width,height,margin可以设置图片属性
# generate 可以对全部文本进行自动分词,但是他对中文支持不好,对中文的分词处理请看我的下一篇文章
#wordcloud = WordCloud(font_path = r'D:\Fonts\simkai.ttf').generate(f)
# 你可以通过font_path参数来设置字体集
#background_color参数为设置背景颜色,默认颜色为黑色
import matplotlib.pyplot as plt
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordcloud.to_file('test.png')

# 이미지를 저장하지만 세 번째 모듈의 예에서는 이미지 크기가 마스크에 따라 저장됩니다

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

글꼴 색상을 맞춤설정하세요

이 코드 주로 wordcloud github에서 제공되며, 이 예제는 github에서 다운로드할 수 있습니다

#!/usr/bin/env python
"""
Colored by Group Example
========================
Generating a word cloud that assigns colors to words based on
a predefined mapping from colors to words
"""
from wordcloud import (WordCloud, get_single_color_func)
import matplotlib.pyplot as plt
class SimpleGroupedColorFunc(object):
    """Create a color function object which assigns EXACT colors
       to certain words based on the color to words mapping
       Parameters
       ----------
       color_to_words : dict(str -> list(str))
         A dictionary that maps a color to the list of words.
       default_color : str
         Color that will be assigned to a word that's not a member
         of any value from color_to_words.
    """
    def __init__(self, color_to_words, default_color):
        self.word_to_color = {word: color
                              for (color, words) in color_to_words.items()
                              for word in words}
        self.default_color = default_color
    def __call__(self, word, **kwargs):
        return self.word_to_color.get(word, self.default_color)
class GroupedColorFunc(object):
    """Create a color function object which assigns DIFFERENT SHADES of
       specified colors to certain words based on the color to words mapping.
       Uses wordcloud.get_single_color_func
       Parameters
       ----------
       color_to_words : dict(str -> list(str))
         A dictionary that maps a color to the list of words.
       default_color : str
         Color that will be assigned to a word that's not a member
         of any value from color_to_words.
    """
    def __init__(self, color_to_words, default_color):
        self.color_func_to_words = [
            (get_single_color_func(color), set(words))
            for (color, words) in color_to_words.items()]
        self.default_color_func = get_single_color_func(default_color)
    def get_color_func(self, word):
        """Returns a single_color_func associated with the word"""
        try:
            color_func = next(
                color_func for (color_func, words) in self.color_func_to_words
                if word in words)
        except StopIteration:
            color_func = self.default_color_func
        return color_func
    def __call__(self, word, **kwargs):
        return self.get_color_func(word)(word, **kwargs)
text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
# Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(collocations=False).generate(text.lower())
# 自定义所有单词的颜色
color_to_words = {
    # words below will be colored with a green single color function
    '#00ff00': ['beautiful', 'explicit', 'simple', 'sparse',
                'readability', 'rules', 'practicality',
                'explicitly', 'one', 'now', 'easy', 'obvious', 'better'],
    # will be colored with a red single color function
    'red': ['ugly', 'implicit', 'complex', 'complicated', 'nested',
            'dense', 'special', 'errors', 'silently', 'ambiguity',
            'guess', 'hard']
}
# Words that are not in any of the color_to_words values
# will be colored with a grey single color function
default_color = 'grey'
# Create a color function with single tone
# grouped_color_func = SimpleGroupedColorFunc(color_to_words, default_color)
# Create a color function with multiple tones
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
# Apply our color function
# 如果你也可以将color_func的参数设置为图片,详细的说明请看 下一部分
wc.recolor(color_func=grouped_color_func)
# Plot
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.


배경 이미지를 사용하여 단어 구름을 생성하고 중지 단어 세트를 설정하세요

이 코드는 주로 wordcloud의 github에서 제공됩니다. 또한 github

#!/usr/bin/env python
"""
Image-colored wordcloud
=======================
You can color a word-cloud by using an image-based coloring strategy
implemented in ImageColorGenerator. It uses the average color of the region
occupied by the word in a source image. You can combine this with masking -
pure-white will be interpreted as 'don't occupy' by the WordCloud object when
passed as mask.
If you want white as a legal color, you can just pass a different image to
"mask", but make sure the image shapes line up.
"""
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()
# read the mask / color image taken from
# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))
# 设置停用词
stopwords = set(STOPWORDS)
stopwords.add("said")
# 你可以通过 mask 参数 来设置词云形状
wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
               stopwords=stopwords, max_font_size=40, random_state=42)
# generate word cloud
wc.generate(text)
# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)
# show
# 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
# 我们还可以直接在构造函数中直接给颜色
# 通过这种方式词云将会按照给定的图片颜色布局生成字体颜色策略
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()

에서 예제와 원본 사진 및 렌더링을 다운로드할 수 있습니다. 디스플레이 효과는 다음과 같습니다:

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.

위 내용은 Python + 단어 구름은 10분 안에 영어 단어 구름을 생성하는 방법을 배웁니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 CSDN에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.Apr 24, 2025 pm 03:41 PM

Inpython, "목록", isaversatile, mutablesequencetatcanholdmixeddatattypes, whilean "array"isamorememory-efficed, homogeneouseceenceRequiringElements ofthesAmeType.1) ListSareIdeAldiversEdatastorageandmanipulationDuetoIrflexibrieth

파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?Apr 24, 2025 pm 03:37 PM

PythonlistsAndarraysareBotheBotheBothebothable.1) ListSareflexibleandsupporterogenousDatabutarabestemory-efficient.2) Arraysaremorememory-efforhomogeneousdatabutlessverstile, CorrectTypecodeusagetoavoidercer가 필요합니다.

Python vs. C : 주요 차이점 이해Python vs. C : 주요 차이점 이해Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Apr 21, 2025 am 12:17 AM

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

파이썬 목표에 도달 : 매일 2 시간의 힘파이썬 목표에 도달 : 매일 2 시간의 힘Apr 20, 2025 am 12:21 AM

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)