将Counter dict对象转换为matplotlib可绘制的对象

时间:2015-10-03 23:53:26

标签: python dictionary matplotlib

我编写了以下代码,从一组不同的新闻网站上回放新闻标题中的热门词:

... # list of headline words is in finale

filtered_word_list = finale[:] #make a copy of the word_list
for word in finale: # iterate over word_list
  if word in stopwords.words('english'):
   filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword
filtlist = str(Counter(filtered_word_list))
line = re.sub('[!@#$-]', '', filtlist)
print(line)

当我尝试通过以下方式绘制时:

plt.plot(line)

我收到以下错误:

ValueError: could not convert string to float: 'Counter({**BIG LONG LIST OF WORDS IT FOUND THAT WOULD MAKE THIS PAGE UNREADABLE**})
/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_gtk3.py:215: Warning: Source ID 7 was not found when attempting to remove it
  GLib.source_remove(self._idle_event_id)

我对如何正确使用 matplotlib (以及 pyplot 模块)了解如何转换计数器知之甚少dict对象将它吐出到matplotlib可以用pyplot绘制的dict对象中。

你们是否有任何关于我如何开始解决这个问题的想法?

2 个答案:

答案 0 :(得分:3)

一种可能的解决方案是使用re.sub而不将Counter转换为字符串,然后使用Counter.keys

为了绘图,您可以将Counter转储到pandas DF。

from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt

list = ["#hello", "@someguy","#hello", "@someguy"]

d = Counter(list)

key = d.keys()

df = pd.DataFrame(d,index=key)
df.drop(df.columns[1:], inplace=True)

df.plot(kind='bar')

plt.show()

如果您将Counter作为collections.Counter课程,则可以更轻松地进行绘制。您遇到的问题是您正在尝试绘制str

答案 1 :(得分:1)

您可以将计数器对象转换为private Point startuplocation; private void Form1_Load(object sender, EventArgs e) { this.startuplocation = this.Location; this.Location = new Point(-1000, -1000); } private void Form1_Shown(object sender, EventArgs e) //fires first time shown { this.Visible = false; this.Location = this.startuplocation; } 的列表。您可以使用list(Counter...)Counter(...).items()keys()获取商品,键,值。这只是一本字典。