检查数据框中单词密度的函数

Function to check word density in a Dataframe

请帮我用代码做一个函数。谢谢

my_words = ''

for w in data3['any_column'].astype(str).values:
    my_words += '{} '.format(w.lower())
my_words = my_words.split(' ')
word_counter = {}
for w in my_words:
    if w not in word_counter:
        word_counter[w] = 1
    if w in word_counter:
        word_counter[w] += 1
word_counter_series = pd.Series(word_counter)
word_counter_series.sort_values(ascending=False)

一个更简单的替代方法是使用 Counter class.

from collections import Counter
counts = Counter(my_words)

结果将是一个类似字典的对象,它关联单词以及它们在列表中出现的次数。

您可以使用 Counter 来完成。这是一个例子:

from collections import Counter

def word_counter(text):
    words_list = text.split(" ")
    return Counter(words_list)

您还可以查看 this question's 第二个答案了解更多详情。