使用Dictionary来计算出现次数(Using Dictionary to count the number of appearances)

编程入门 行业动态 更新时间:2024-10-13 22:23:07
使用Dictionary来计算出现次数(Using Dictionary to count the number of appearances)

我的问题是我试图从文本框中取出一段文本,例如“花了一天时间”插入着名的名字“'#excited #happy #happy”

然后我想计算每个主题标签出现在主体中的次数,可以是任意长度的文本。

所以上面会回来的

兴奋= 1

快乐= 2

我打算使用字典,但我不确定如何实现搜索标签并添加到字典中。

这就是我到目前为止所做的一切

string body = txtBody.Text; Dictionary<string, string> dic = new Dictionary<string, string>(); foreach(char c in body) { }

谢谢你的帮助

My problem is that I am trying to take a body of text from a text box for example "Spent the day with "insert famous name" '#excited #happy #happy"

then I want to count how many times each hashtag appears in the body, which can be any length of text.

so the above would return this

excited = 1

happy = 2

I Was planning on using a dictionary but I am not sure how I would implement the search for the hashtags and add to the dictionary.

This is all I have so far

string body = txtBody.Text; Dictionary<string, string> dic = new Dictionary<string, string>(); foreach(char c in body) { }

thanks for any help

最满意答案

这可以通过几种LINQ方法实现:

var text = "Spent the day with <insert famous name> #excited #happy #happy"; var hashtags = text.Split(new[] { ' ' }) .Where(word => word.StartsWith("#")) .GroupBy(hashtag => hashtag) .ToDictionary(group => group.Key, group => group.Count()); Console.WriteLine(string.Join("; ", hashtags.Select(kvp => kvp.Key + ": " + kvp.Value)));

这将打印出来

#excited: 1; #happy: 2

This can be achieved with a couple of LINQ methods:

var text = "Spent the day with <insert famous name> #excited #happy #happy"; var hashtags = text.Split(new[] { ' ' }) .Where(word => word.StartsWith("#")) .GroupBy(hashtag => hashtag) .ToDictionary(group => group.Key, group => group.Count()); Console.WriteLine(string.Join("; ", hashtags.Select(kvp => kvp.Key + ": " + kvp.Value)));

This will print

#excited: 1; #happy: 2

更多推荐

本文发布于:2023-08-07 16:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:次数   Dictionary   count   appearances   number

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!