【问题标题】:Array of tuples necessary for generate_from_frequencies method in Python wordcloudPython wordcloud 中 generate_from_frequencies 方法所需的元组数组
【发布时间】:2016-11-09 21:36:53
【问题描述】:

我正在尝试根据字符串的重要性及其在 Excel 文档中的相应数据值在 Python 中制作词云。 generate_from_frequencies 方法采用频率参数,文档说该参数应该采用元组数组。

来自wordcloud source code的部分代码:

def generate_from_frequencies(self, frequencies):
    """Create a word_cloud from words and frequencies.
    Parameters
    ----------
    frequencies : array of tuples
        A tuple contains the word and its frequency.
    Returns
    -------
    self
    """
    # make sure frequencies are sorted and normalized
    frequencies = sorted(frequencies, key=item1, reverse=True)
    frequencies = frequencies[:self.max_words]
    # largest entry will be 1
    max_frequency = float(frequencies[0][1])

    frequencies = [(word, freq / max_frequency) for word, freq in frequencies]

我尝试使用常规列表,然后尝试使用 numpy 的 ndarray,但 PyCharm 显示参数类型应为 array.py 的警告,我读取的该参数类型仅应采用字符、整数和浮点数(@ 987654322@):

该模块定义了一种对象类型,可以紧凑地表示一组基本值:字符、整数、浮点数。

我的测试代码:

import os
import numpy
import wordcloud

d = os.path.dirname(__file__)
cloud = wordcloud.WordCloud()
array = numpy.array([("hi", 6), ("seven"), 17])
cloud.generate_from_frequencies(array)  # <= what should go in the parentheses

如果我在 PyCharm 警告的情况下运行上面的代码,我会收到以下错误,我想这是告诉我它不能接受 ndarray 类型的另一种方式:

  File "C:/Users/Caitlin/Documents/BioDataSorter/tag_cloud_test.py", line 8, in <module>
cloud.generate_from_frequencies(array)  # <= what should go in the parentheses
  File "C:\Python34\lib\site-packages\wordcloud\wordcloud.py", line 263, in generate_from_frequencies
frequencies = sorted(frequencies, key=item1, reverse=True)
TypeError: 'int' object is not subscriptable

另一个潜在的问题可能是 wordcloud 是用 Python 2 编写的,但我使用的是 Python 3.4,这可能导致某些代码无法使用。我应该通过什么类型的方法?

【问题讨论】:

    标签: python arrays word-cloud


    【解决方案1】:

    来自您的测试代码 ... # &lt;= 这个括号里应该写什么

    我相信你应该有一个元组(("hi", float(6/(6+17)),("seven", float(17/(6+17))))

    【讨论】:

    • 感谢您的回答!我将该行更改为:cloud.generate_from_frequencies((("hi", float(6/(6+17)),("seven", float(17/(6+17)))))),但我得到一个 TypeError: Float object is not subscriptable,所以我将 float 更改为 int 并且它起作用了。
    【解决方案2】:

    感谢 J Herron 和 selva 提供了使用元组而不是列表对象的答案——我最终得到了这个:

    cloud.generate_from_frequencies((("hi", 3),("seven", 7)))
    

    它仍然是我的 IDE 中的一个错误,这具有误导性,但它按预期的方式工作。

    【讨论】:

    • 正是由于某种原因,这行代码对我不起作用.. AttributeError: 'tuple' object has no attribute 'items' 用字典尝试-然后错误是 int 不可迭代。跨度>
    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多