【问题标题】:C# File to Dictionary, but taking pairs of wordsC# 文件到字典,但需要成对的单词
【发布时间】:2015-05-17 17:23:35
【问题描述】:

我正在考虑制作一个字典,其中包含单词对以及文件中的单个单词。

标准的“单字”看起来像:

private Dictionary<string, int> tempDict = new Dictionary<string, int>();
private void GetWords(string[] file)
{ 
   tempDict = file
   .SelectMany(i => File.ReadLines(i)
   .SelectMany(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)))
   .GroupBy(word => word)                    
   .ToDictionary(g => g.Key, g => g.Count());
}

还有字符串:

亚当喜欢咖啡

将是:

亚当;喜欢;咖啡

但我想让它也匹配对(但只匹配相邻的)所以它看起来像:

亚当;亚当喜欢;喜欢;喜欢咖啡;咖啡

我不确定这是否可行,需要一些帮助。

【问题讨论】:

  • 您在寻找 LINQ 解决方案吗?
  • @AlexeiLevenkov 最好
  • 您希望如何对结果进行分组?
  • @YuvalItzchakov 字典将由它制成,看起来像 {Adam, 1} {Adam likes, 1} 等等。所以按短语分组?

标签: c# string linq dictionary


【解决方案1】:

MoreLINQ 有一个 Enumerable.Pairwise,它采用当前和前一个值以及一个投影函数。

返回将函数应用于源序列中的每个元素及其前驱元素的序列,但第一个元素除外,它仅作为第二个元素的前驱元素返回。

将其与原始拆分值数组连接会输出:

var sentence = "Adam likes coffee";
var splitWords = sentence.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var pairWise = splitWords.Pairwise((first, second) => string.Format("{0} {1}", first,
                                                                               second))
                         .Concat(splitWords)
                         .GroupBy(x => x)
                         .ToDictionary(x => x.Key, x => x.Count())

会导致:

【讨论】:

  • 如果我要对文件中的单词做更多的工作,例如.ToLower().Distinct(),我需要对它们都使用它吗?因为第一个只是我所知道的一个字符串,如果只是在第二个中,它应该在.Concat()之后吗?
  • 在你Split之后你可以用var lowerCased = sentence.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(string =&gt; string.ToLower());处理之前将所有字母小写
  • @YuvalItzchakov - 为什么使用非标准的Pairwise Zip 就可以了?
猜你喜欢
  • 2017-02-16
  • 1970-01-01
  • 2012-09-02
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多