Python: как определить частотность слов в тексте

Для того, чтобы определить частоту употребления слов в каком-либо тексте, можно воспользоваться замечательной библиотекой wordcloud. Кстати, она не входит в стандартный набор Anaconda, поэтому ее нужно поставить отдельно командой: pip install wordcloud.

Чтобы составить карту частотности употребления слов, можно сделать так:

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt

text = "Declarative visualization grammars can accelerate development, facilitate retargeting across platforms, and allow language-level optimizations. However, existing declarative visualization languages are primarily concerned with visual encoding, and rely on imperative event handlers for interactive behaviors. In response, we introduce a model of declarative interaction design for data visualizations. Adopting methods from reactive programming, we model low-level events as composable data streams from which we form higher-level semantic signals. Signals feed predicates and scale inversions, which allow us to generalize interactive selections at the level of item geometry (pixels) into interactive queries over the data domain. Production rules then use these queries to manipulate the visualization’s appearance. To facilitate reuse and sharing, these constructs can be encapsulated as named interactors: standalone, purely declarative specifications of interaction techniques. We assess our model’s feasibility and expressivity by instantiating it with extensions to the Vega visualization grammar. Through a diverse range of examples, we demonstrate coverage over an established taxonomy of visualization interaction techniques."

stopwords = set(STOPWORDS)
wordcloud = WordCloud(stopwords=stopwords, background_color="white").generate(text)

plt.figure(figsize=(15,10))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

В итоге вы получите что-то вроде этого:wordcloud частота слов в тексте

Часто бывает необходимо вытащить текст из свойств датафрейма и предварительно его почистить, это можно сделать при помощи регулярок, вот пример готовой функции:

import pandas as pd
import re

# пример функции, которая чистит от лишних символов текст, спарсенный из твиттера
def clean(text):
    text = str(text).lower()
    text = re.sub('\[.*?\]', '', text)
    text = re.sub('https?://\S+|www\.\S+', '', text)
    text = re.sub('<.*?>+', '', text)
    text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
    text = re.sub('\n', '', text)
    text = re.sub('\w*\d\w*', '', text)
    text = [word for word in text.split(' ') if word not in stopword]
    text=" ".join(text)
    text = [stemmer.stem(word) for word in text.split(' ')]
    text=" ".join(text)
    return text

data["text"] = data["text"].apply(clean)
text = " ".join(i for i in data.text)

 

Рейтинг
( 65 оценок, среднее 2.98 из 5 )
Понравилась статья? Поделиться с друзьями: