python从字典生成词云_Python | 生成从1到N的数字及其平方(i,i * i)的字典

python从字典生成词云

Given a number N, and we have to generate a dictionary that contains numbers and their squares (i, i*i) using Python.

给定一个数字N,我们必须使用Python生成一个包含数字及其平方(i,i * i)的字典。

Example:

例:

    Input: 
    n = 10 
    Output:
    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Program:

程序:

# Python program to generate and print 
# dictionary of numbers and square (i, i*i)

# declare and assign n
n = 10

# declare dictionary 
numbers = {}

# run loop from 1 to n 
for i in range(1, n+1):
	numbers[i] = i * i

# print dictionary 
print numbers

Output

输出量

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}


翻译自: https://www.includehelp.com/python/generate-dictionary-of-numbers-and-their-squares-from-1-to-N.aspx

python从字典生成词云

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了生成词云,我们需要先读取文本文件并进行分词。然后,我们可以使用Python中的字典来保存需要去重的词,并计算每个词出现的次数。最后,我们可以使用第三方库wordcloud来生成词云。 以下是一个简单的Python程序,用于生成三国演义中常见人名的词云: ```python import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt # 读取文本文件 with open('threekingdoms.txt', 'r', encoding='utf-8') as f: text = f.read() # 对文本进行分词 words = jieba.cut(text) # 创建一个字典 word_dict = {} # 遍历分词结果,统计每个词出现的次数 for word in words: if len(word) < 2: continue if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 # 生成词云 wc = WordCloud(background_color='white', font_path='msyh.ttc', width=800, height=600) wc.generate_from_frequencies(word_dict) # 显示词云 plt.imshow(wc) plt.axis('off') plt.show() # 输出词频最高的5个词 top_words = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)[:5] print('词频最高的5个词:') for word, frequency in top_words: print(word, frequency) ``` 在这个程序中,我们首先使用jieba库对文本进行分词,并创建一个字典来保存需要去重的词。然后,我们遍历分词结果,统计每个词出现的次数,并将结果保存到字典中。接下来,我们使用wordcloud库生成词云,并使用matplotlib库显示词云。最后,我们输出词频最高的5个词。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值