VC word cloud on knee

  • Tutorial
Recently, I sharply wanted to find out how often the word "coffee" is found in the public of my friend, as well as to build a beautiful cloud of words, based on the frequency of their appearance in posts.
If you are interested in how to do it literally on your knees using C #, then please, under cat.

Because this application was written on my knee and the only task was to amuse my curiosity, it was decided to divide it into 2 stages: get the words and save to a file, clean all prepositions from it with pens, and then build a cloud from the received file.
For some more serious task, it is worth using dictionaries of prepositions, endings or some other alternative options.

Getting data from VK

First, install the appropriate library . We create the VK application.

var services = new ServiceCollection();
var vkApi = new VkApi(services);

We will authorize, although this stage can be skipped, but then the number of available "walls" in VK will sharply decrease.

 vkApi.Authorize(new ApiAuthParams
                { AccessToken = "ваш токен",Settings = Settings.All});


vkApi.Authorize(new ApiAuthParams
		Login = "Login",
		Password = "Password",
		Settings = Settings.All

We get the last 100 posts on the selected wall.

var posts=vkApi.Wall.Get(new WallGetParams
                OwnerId = (long)IdНужнойСтены,// для сообществ id должно начинаться с -
                Count = 100

From the existing collection we make one large line.

foreach (var post in posts.WallPosts)
                if (!string.IsNullOrEmpty(post.Text))
                    data += post.Text;

Further, you can clear the selected line from punctuation marks.

 data = Regex.Replace(data, "\\!|\\?|\\(|\\)|\"|\\#|\\,|»|«|-", string.Empty);

Well, let's get a collection of words.

 var words = data.Split(default(Char[]), StringSplitOptions.RemoveEmptyEntries).ToList();

At the penultimate stage, we compose a dictionary with the frequency of words.

var wordsDictionary = new Dictionary();
foreach (var word in words)
            if (wordsDictionary.ContainsKey(word.ToLower()))
                wordsDictionary[word.ToLower()] += 1;

At the end, we sort it and, if desired, save it to a file.

wordsDictionary = wordsDictionary.OrderByDescending(x => x.Value)
                                 .ToDictionary(x => x.Key, x => x.Value);

Moving on to creating a word cloud

To do this, you must add the dependency System.Drawing to the project and this package .

Add dependency to our application.

using WordCloudGen = WordCloud.WordCloud;

And we form the image.

            var wc = new WordCloudGen(1024, 1024);
            Console.WriteLine("pict create");

In conclusion, I want to say thank you to the user worldbeater and recall that the library for VK has great support in tg . By the way, the word "coffee" for 100 posts occurred 142 times.

Also popular now: