这个C#代码出了什么问题

时间:2013-05-06 16:40:33

标签: c# information-retrieval inverted-index

我尝试创建倒置索引,但它不起作用。我的代码没有错误但不起作用。怎么了?

我每次都会收到此异常:KeyNotFoundException was unhandled : the given Key was not present in the dictionary

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace ConsoleApplication1
{
     class Program
     {
        static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
        {
            return dictionary
              .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))
            .GroupBy(keyValuePair => keyValuePair.Key)
            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));
        }

        static void Main(string[] args)
        {
            Console.WriteLine("files: ");
            //read all the text document on the specified directory; change this directory based on your machine
            foreach (string file in Directory.EnumerateFiles("D:\\IR\\", "*.txt"))
            {
            string contents = File.ReadAllText(file);
            Console.WriteLine(contents);
            Console.Write("find: ");
            var find = Console.ReadLine();
            var dictionary = file.Split().ToDictionary(files => files, files => File.ReadAllText(file).Split().AsEnumerable());
            Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find]));
            }
         }
     }
}

我编辑了代码,现在它没有错误和异常。现在还有另外一个问题,它必须只能读取所有文件一次,但它不能意味着它每次读取其中一个然后执行查找过程而且这不是我的观点我需要一个像我写的下面的输出。我似乎应该将foreach(string file in Dictionary.EnumerateFiles("D:\\IR\\","*.txt"))更改为其他内容。但我不知道它是什么。

输出应该是这样的:

文件:file1 file2 file3

找到:什么

发现于:file1 file2

1 个答案:

答案 0 :(得分:0)

修改:我测试了您的Invert版本,看起来效果很好。您是否对默认的ToString()输出感到困惑?如果您直接尝试打印Program.Invert(dictionary)[find],则无法获得预期的输出,因为默认的ToString()不是很有帮助(因为您尝试打印的对象不会覆盖{{ 1}})。您将不得不遍历您的值列表并单独打印每个值。假设object.ToString()覆盖TKey,您将获得所需的输出。例如,

ToString()

上一个答案(为子孙后代保存): 好吧,你提到你的Console.WriteLine("{0} found in: ", find); foreach (var val in Program.Invert(dictionary)[find]) { Console.WriteLine(val); } 方法出了问题。我试着写一个我自己的Invert方法,这就是我想出来的。我已经将方法调用分解为单独的部分,以便清楚我正在做什么。

Invert