aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Tests/ConsistencyTests/TextIndexing/IndexBuilder.cs
blob: 4c46f47932c969ae25565540de02096d1eae7034 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MediaBrowser.Tests.ConsistencyTests.TextIndexing
{
    public class IndexBuilder
    {
        public const int MinumumWordLength = 4;

        public static char[] WordChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();

        public static WordIndex BuildIndexFromFiles(IEnumerable<FileInfo> wordFiles, string rootFolderPath)
        {
            var index = new WordIndex();

            var wordSeparators = Enumerable.Range(32, 127).Select(e => Convert.ToChar(e)).Where(c => !WordChars.Contains(c)).ToArray();
            wordSeparators = wordSeparators.Concat(new[] { '\t' }).ToArray(); // add tab

            foreach (var file in wordFiles)
            {
                var lineNumber = 1;
                var displayFileName = file.FullName.Replace(rootFolderPath, string.Empty);
                using (var reader = file.OpenText())
                {
                    while (!reader.EndOfStream)
                    {
                        var words = reader
                             .ReadLine()
                             .Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries);
                        ////.Select(f => f.Trim());

                        var wordIndex = 1;
                        foreach (var word in words)
                        {
                            if (word.Length >= MinumumWordLength)
                            {
                                index.AddWordOccurrence(word, displayFileName, file.FullName, lineNumber, wordIndex++);
                            }
                        }

                        lineNumber++;
                    }
                }
            }

            return index;
        }

    }
}