7

我正在阅读文档,并拆分单词以获取字典中的每个单词,但是我怎么能排除一些单词(例如“the/a/an”)。

这是我的功能:

private void Splitter(string[] file)
{
    try
    {
        tempDict = file
            .SelectMany(i => File.ReadAllLines(i)
            .SelectMany(line => line.Split(new[] { ' ', ',', '.', '?', '!', }, StringSplitOptions.RemoveEmptyEntries))
            .AsParallel()
            .Distinct())
            .GroupBy(word => word)
            .ToDictionary(g => g.Key, g => g.Count());
    }
    catch (Exception ex)
    {
        Ex(ex);
    }
}

另外,在这种情况下,添加.ToLower()调用以使文件中的所有单词都变为小写的正确位置在哪里?temp = file在( ..)之前我正在考虑这样的事情:

file.ToList().ConvertAll(d => d.ToLower());
4

2 回答 2

4

你想过滤掉停用词吗?

 HashSet<String> StopWords = new HashSet<String> { 
   "a", "an", "the" 
 }; 

 ...

 tempDict = file
   .SelectMany(i => File.ReadAllLines(i)
   .SelectMany(line => line.Split(new[] { ' ', ',', '.', '?', '!', }, StringSplitOptions.RemoveEmptyEntries))
   .AsParallel()
   .Select(word => word.ToLower()) // <- To Lower case 
   .Where(word => !StopWords.Contains(word)) // <- No stop words
   .Distinct()
   .GroupBy(word => word)
   .ToDictionary(g => g.Key, g => g.Count());

但是,此代码是部分解决方案:像Berlin这样的专有名称将被转换为小写:berlin以及首字母缩略词:KISS (Keep It Simple, Stupid) 将变为只是一个,一些数字将不正确

于 2015-05-15T07:20:20.427 回答
1

我会这样做:

var ignore = new [] { "the", "a", "an" };
tempDict = file
    .SelectMany(i =>
        File
            .ReadAllLines(i)
            .SelectMany(line =>
                line
                    .ToLowerInvariant()
                    .Split(
                        new[] { ' ', ',', '.', '?', '!', },
                        StringSplitOptions.RemoveEmptyEntries))
                    .AsParallel()
                    .Distinct())
    .Where(x => !ignore.Contains(x))
    .GroupBy(word => word)
    .ToDictionary(g => g.Key, g => g.Count());

如果性能成为问题,您可以更改ignoreHashSet<string>,但由于您使用的是文件 IO,所以不太可能。

于 2015-05-15T07:22:58.770 回答