Counter() 并绘制文本中最常见的单词

bra*_*apa 6 python counter matplotlib

我编写了一个函数,可以输出并绘制文本中最常见的单词。请参阅下面的代码和输出。

tf = Counter()
for i  in list(tweet['text']):
    temp=XXX 
for tag, count in tf.most_common(20):
        print("{}: {}".format(tag, count))   
        
y = [count for tag, count in tf.most_common(20)]
x = range(1, len(y)+1)

plt.bar(x, y)
plt.title("Term frequencies used inTwitter Data")
plt.ylabel("Frequency")
plt.savefig('us-iran-term-distn.png')
Run Code Online (Sandbox Code Playgroud)

输出是最常见的单词,如下图所示:

blacklivesmatter: 127336
blm: 58619
black: 25973
people: 17960
.
.
lives: 11684
police: 10762
matter: 9902
white: 9766
georgefloyd: 9023
protest: 8734
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请问如何在 x 轴上添加最常用的单词?

非常感谢

Joh*_*anC 11

您可以直接使用 x 值的标签列表。Matplotlib 会将这些文本显示为轴的刻度标签。或者,可以使用 useplt.yscale('log')来更好地区分较低的值。

下面的代码首先生成一个随机单词列表,遵循 zipf 分布。

from collections import Counter
import numpy as np
from matplotlib import pyplot as plt

words = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Brown', 'Magenta', 'Tan', 'Cyan', 'Olive', 'Maroon', 'Navy', 'Aquamarine', 'Turquoise', 'Silver', 'Lime', 'Teal', 'Indigo', 'Violet', 'Pink', 'Black', 'White', 'Gray']
indices = np.random.zipf(1.6, size=100000).astype(np.int) % len(words)
tweets = np.array(words)[indices]

tf = Counter(tweets)

y = [count for tag, count in tf.most_common(20)]
x = [tag for tag, count in tf.most_common(20)]

plt.bar(x, y, color='crimson')
plt.title("Term frequencies in Twitter Data")
plt.ylabel("Frequency (log scale)")
plt.yscale('log') # optionally set a log scale for the y-axis
plt.xticks(rotation=90)
for i, (tag, count) in enumerate(tf.most_common(20)):
    plt.text(i, count, f' {count} ', rotation=90,
             ha='center', va='top' if i < 10 else 'bottom', color='white' if i < 10 else 'black')
plt.xlim(-0.6, len(x)-0.4) # optionally set tighter x lims
plt.tight_layout() # change the whitespace such that all labels fit nicely
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果图