计数器()并打印文本中最常用的单词

2024-04-27 03:15:02 发布

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

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

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')

输出是最常见的单词,下面有一个图:

blacklivesmatter: 127336
blm: 58619
black: 25973
people: 17960
.
.
lives: 11684
police: 10762
matter: 9902
white: 9766
georgefloyd: 9023
protest: 8734

enter image description here

我怎样才能在x轴上加上最常用的单词

非常感谢


Tags: 函数代码in文本mostfortftag
1条回答
网友
1楼 · 发布于 2024-04-27 03:15:02

可以直接使用x值的标记列表。Matplotlib将这些文本显示为轴的标签。或者,use可以使用plt.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()

resulting plot

相关问题 更多 >