我需要计算每个关键字多少次重复发生在一个字符串,通过次数最多的排序。 用于此目的的.NET代码中可用的最快算法是什么?关键字.NET
关键字.NET
回答
编辑:下面的代码组,计
string[] target = src.Split(new char[] { ' ' });
var results = target.GroupBy(t => new
{
str = t,
count = target.Count(sub => sub.Equals(t))
});
这终于开始让我更有意义的独特记号......
编辑:下面的子目标相关的计数结果代码:
string src = "for each character in the string, take the rest of the " +
"string starting from that character " +
"as a substring; count it if it starts with the target string";
string[] target = {"string", "the", "in"};
var results = target.Select((t, index) => new {str = t,
count = src.Select((c, i) => src.Substring(i)).
Count(sub => sub.StartsWith(t))});
结果现在是:
+ [0] { str = "string", count = 4 } <Anonymous Type>
+ [1] { str = "the", count = 4 } <Anonymous Type>
+ [2] { str = "in", count = 6 } <Anonymous Type>
下面
原始代码:
string src = "for each character in the string, take the rest of the " +
"string starting from that character " +
"as a substring; count it if it starts with the target string";
string[] target = {"string", "the", "in"};
var results = target.Select(t => src.Select((c, i) => src.Substring(i)).
Count(sub => sub.StartsWith(t))).OrderByDescending(t => t);
与感激确认给this previous response。从调试
结果(这需要额外的逻辑包括匹配的字符串,其计数):
- results {System.Linq.OrderedEnumerable<int,int>}
- Results View Expanding the Results View will enumerate the IEnumerable
[0] 6 int
[1] 4 int
[2] 4 int
现在这很酷。 – 2010-10-27 17:09:20
是的,我需要回去和upvote我的来源。 – 2010-10-27 17:09:59
我不知道它怎么会比蛮力方法来执行(例如只是遍历你正在寻找的关键字,使用的IndexOf找到事件,并指望他们收集器阵列)?我绝不意味着要从这个解决方案的可怕性中脱身,我只是好奇,因为我对linq的效率没有很好的理解。 – 2010-10-27 17:13:28
您可以将字符串分解为一个字符串集合,每个字符一个字符串,然后对该集合执行LINQ查询。虽然我怀疑它会是最快的,但它可能比正则表达式更快。
在读取过程中检查单词/字符的出现之前,我已经实现了单通字符串读取器。您看到这种类型的代码功能用于CSV解析。 – wllmsaccnt 2010-10-27 16:52:39
说不上大约最快的,但LINQ的可能是最理解:
var myListOfKeywords = new [] {"struct", "public", ...};
var keywordCount = from keyword in myProgramText.Split(new []{" ","(", ...})
group by keyword into g
where myListOfKeywords.Contains(g.Key)
select new {g.Key, g.Count()}
foreach(var element in keywordCount)
Console.WriteLine(String.Format("Keyword: {0}, Count: {1}", element.Key, element.Count));
您可以在非LINQ的-Y方式写这篇文章,但基本前提是相同的;将字符串分成单词,并计算每个感兴趣单词的出现次数。
简单算法:将字符串拆分为单词数组,迭代该数组,并将每个单词的计数存储在散列表中。完成后按计数排序。
- 1. .NET 4.0 - “动态”关键字
- 2. .NET语言中的错误关键字
- 3. .net反射和“params”关键字
- 4. 在关键字
- 5. 关键字
- 6. volatile关键字
- 7. DbLookup关键字
- 8. Static关键字
- 9. c#关键字
- 10. autorelease关键字
- 11. 关键字
- 12. Java'this'关键字
- 13. 按键绑定关键字
- 14. Aptana:关闭php else关键字代码关键字
- 15. 关于带关键字的静态关键字的问题
- 16. 关于该volatile关键字
- 17. 关于关键字这个
- 18. 关于“新”的关键字
- 19. 关于`self`的关键字
- 20. 关于return关键字
- 21. 查找从关键字到关键字的字符串部分
- 22. 由struct关键字
- 23. BigDecimal.java关键字“final”
- 24. Android marketplace关键字
- 25. Moodle Meta关键字
- 26. 关键字事件
- 27. 全球关键字
- 28. meta关键字CHARACTERSET
- 29. 关键字错误
- 30. 关键词字典
什么语言?我相信没有内置框架功能可以做到这一点,并且关于如何定义“关键字”的具体细节可能会使其变得复杂,例如,复数,标点符号等等。这是一个有趣的算法问题,但答案将取决于您使用的编程语言。 – 2010-10-27 16:47:58
C#和VB.NET都可以接受。目前不需要排除不必要部分的能力,所有单词都很好。 – SharpAffair 2010-10-27 16:51:08