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

2024-04-25 23:04:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了以下代码,这些代码将一组不同新闻网站的新闻标题中的最上面的单词吐出来:

... # 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)

当我试图通过以下方式来绘制:

^{pr2}$

我得到以下错误:

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模块)知道如何将它吐出的Counter dict对象转换为matplotlib可以用pyplot绘图的dict对象。在

你们有谁知道我该如何着手解决这个问题吗?在


Tags: of代码inifmatplotlibiscounterit
2条回答

您可以使用list(Counter...)将counter对象转换为一个列表。您可以使用Counter(...).items()keys()values()来获取项、键和值。它只是一本字典。在

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

为了绘图,您可以使用Counter并将其转储到pandasDF中。在

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。在

相关问题 更多 >