我刚开始学习Python和机器学习。我想为一个文本文件绘制Zipf分布图,但我的代码出现了错误。以下是我的Python代码:
import refrom itertools import islice#获取我们的医学词汇语料库frequency = {}list(frequency)open_file = open("abp.csv", 'r')file_to_string = open_file.read()words = re.findall(r'(\b[A-Za-z][a-z]{2,9}\b)', file_to_string)#根据词频构建词典for word in words: count = frequency.get(word,0) frequency[word] = count + 1#限制词汇到1000个n = 1000frequency = {key:value for key,value in islice(frequency.items(), 0, n)}#将频率的值转换为numpy数组s = frequency.values()s = np.array(s)#计算Zipf分布并绘制数据a = 2. # 分布参数count, bins, ignored = plt.hist(s[s<50], 50, normed=True)x = np.arange(1., 50.)y = x**(-a) / special.zetac(a)plt.plot(x, y/max(y), linewidth=2, color='r')plt.show()
上述代码产生以下错误:count, bins, ignored = plt.hist(s[s<50], 50, normed=True)
TypeError: ‘<‘ not supported between instances of ‘dict_values’ and ‘int’
回答:
实际上,numpy数组s
包含的是一个dict_values
对象。要将这些值转换为包含dict_values
数字的numpy数组,请使用
import numpy as npfrequency = {key:value for key,value in islice(frequency.items(), 0, n)}s = np.fromiter(frequency.values(), dtype=float)
假设您希望数组包含float
类型的数据。
有关更多信息,请阅读文档。