膝盖上的VC词云

最近,我非常想知道“咖啡”一词在我的朋友的公众场合被发现的频率,并根据出现在帖子中的频率来构建一朵美丽的词云。
如果您对使用C#实际在膝盖上进行操作感兴趣,请在cat下使用。

注意事项
因为 这个应用程序是我的膝盖上写的,唯一的任务是逗我好奇心,决定将其分为两个阶段:获取单词并将其保存到文件中,用笔清除其中的所有介词,然后从接收到的文件中构建一个云。
对于一些更严肃的任务,值得使用介词,结尾或其他替代选项的字典。

从VK获取数据


首先,安装适当的 。 我们创建VK应用程序。

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

我们将授权,尽管可以跳过此阶段,但是VK中可用的“墙”的数量将急剧减少。

  vkApi.Authorize(new ApiAuthParams { AccessToken = " ",Settings = Settings.All}); 

或:

 vkApi.Authorize(new ApiAuthParams { Login = "Login", Password = "Password", Settings = Settings.All }); 

我们会在选定的墙上获得最近的100个帖子。

 var posts=vkApi.Wall.Get(new WallGetParams { OwnerId = (long)Id,//   id    - Count = 100 }); 

从现有的收藏中,我们进行了一条大系列。

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

此外,您可以从标点符号清除选定的行。

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

好吧,让我们收集一些单词。

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

在倒数第二阶段,我们用单词的频率组成一本字典。

 var wordsDictionary = new Dictionary<string, int>(); foreach (var word in words) { if (wordsDictionary.ContainsKey(word.ToLower())) wordsDictionary[word.ToLower()] += 1; else { wordsDictionary.Add(word.ToLower(),1); } } 

最后,我们对其进行排序,并根据需要将其保存到文件中。

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

继续创建词云


为此,必须将依赖项System.Drawing添加到项目和此package中

向我们的应用程序添加依赖项。

 using WordCloudGen = WordCloud.WordCloud; 

然后我们形成图像。

  var wc = new WordCloudGen(1024, 1024); wc.Draw(wordsDictionary.Keys.ToList(), wordsDictionary.Values.ToList()) .Save("cloudwords.jpg"); Console.WriteLine("pict create"); 

最后,我想对用户worldbeater表示感谢,并回顾VK库在tg中有很大的支持。 顺便说一下,“咖啡”一词有100个帖子,出现了142次。

Source: https://habr.com/ru/post/zh-CN458524/


All Articles