简体   繁体   English

在Python中创建词云-使单词大小不同?

[英]Creating Word Cloud in Python — Making Words Different Sizes?

I am trying to create a word cloud in python using pytagcloud . 我正在尝试使用pytagcloud在python中创建词云。 With my current cloud, I can generate a cloud, but the words all are the same size. 使用当前的云,我可以生成云,但是所有单词的大小相同。 How can I alter the code so that my words' sizes appear in relation to their frequency? 如何更改代码,以使单词的大小与出现的频率有关?

My text file already has the words with their respective frequency counts already in it, the format is like "George, 44" newline "Harold, 77", newline, "Andrew, 22", newline, etc. However, when it displays the word, it also displays the frequency with it. 我的文本文件中已经包含具有各自频率计数的单词,其格式类似于“ George,44”换行符“ Harold,77”,换行符,“ Andrew,22”,换行符,等等。但是,当显示单词,它也会显示频率。

with open ("MyText.txt", "r") as file:
   Data =file.read().replace('\n', '')

tags = make_tags(get_tag_counts(Data), maxsize=150)

create_tag_image(tags, 'Sample.png', size=(1200, 1200),background=(0, 0, 0, 255),  fontname='Lobstero', rectangular=True)

import webbrowser
webbrowser.open('Sample.png')

You need to cast the result into a tuple. 您需要将结果转换为元组。 Using your question as input text we get the expected result: 使用您的问题作为输入文本,我们得到预期的结果:

from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts

TEXT = '''I am trying to create a word cloud in python. With my current cloud, I can generate a cloud, but the words all are the same size. How can I alter the code so that my words' sizes appear in relation to their frequency?'''

counts = get_tag_counts(TEXT)
tags = make_tags(counts, maxsize=120)
create_tag_image(tags, 'cloud_large.png', size=(900, 600), fontname='Lobster')

在此处输入图片说明

It is worth looking at the variable counts : 值得看一下变量counts

[('cloud', 3), 
('words', 2), 
('code', 1), 
('word', 1), 
('appear', 1), ...

which is simply a list of tuples. 这只是一个元组列表。 Since your input text file contains a list of tuples, you simply need to pass that information into make_tags . 由于您的输入文本文件包含一个元组列表,因此您只需要将该信息传递到make_tags

Edit: You can read a file like this 编辑:您可以读取这样的文件

counts = []
with open("tag_file.txt") as FIN:
   for line in FIN:
       # Assume lines look like: word, number
       word,n = line.strip().split()
       word = word.replace(',','')
       counts.append([word,int(n)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM