1
|
/*
|
2
|
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
|
3
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
4
|
of this software and associated documentation files (the "Software"), to deal
|
5
|
in the Software without restriction, including without limitation the rights
|
6
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7
|
copies of the Software, and to permit persons to whom the Software is
|
8
|
furnished to do so, subject to the following conditions:
|
9
|
|
10
|
The above copyright notice and this permission notice shall be included in
|
11
|
all copies or substantial portions of the Software.
|
12
|
|
13
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19
|
SOFTWARE.
|
20
|
*/
|
21
|
|
22
|
// C5 example: File index: read a text file, build and print a list of
|
23
|
// words and the line numbers (without duplicates) on which they occur.
|
24
|
|
25
|
// Compile with
|
26
|
// csc /r:C5.dll Fileindex.cs
|
27
|
|
28
|
using System; // Console
|
29
|
using System.IO; // StreamReader, TextReader
|
30
|
using System.Text.RegularExpressions; // Regex
|
31
|
using C5; // IDictionary, TreeDictionary, TreeSet
|
32
|
|
33
|
namespace FileIndex
|
34
|
{
|
35
|
class Fileindex
|
36
|
{
|
37
|
static void Main(String[] args)
|
38
|
{
|
39
|
if (args.Length != 1)
|
40
|
Console.WriteLine("Usage: Fileindex <filename>\n");
|
41
|
else
|
42
|
{
|
43
|
IDictionary<String, TreeSet<int>> index = IndexFile(args[0]);
|
44
|
PrintIndex(index);
|
45
|
}
|
46
|
}
|
47
|
|
48
|
static IDictionary<String, TreeSet<int>> IndexFile(String filename)
|
49
|
{
|
50
|
IDictionary<String, TreeSet<int>> index = new TreeDictionary<String, TreeSet<int>>();
|
51
|
Regex delim = new Regex("[^a-zA-Z0-9]+");
|
52
|
using (TextReader rd = new StreamReader(filename))
|
53
|
{
|
54
|
int lineno = 0;
|
55
|
for (String line = rd.ReadLine(); line != null; line = rd.ReadLine())
|
56
|
{
|
57
|
String[] res = delim.Split(line);
|
58
|
lineno++;
|
59
|
foreach (String s in res)
|
60
|
if (s != "")
|
61
|
{
|
62
|
if (!index.Contains(s))
|
63
|
index[s] = new TreeSet<int>();
|
64
|
index[s].Add(lineno);
|
65
|
}
|
66
|
}
|
67
|
}
|
68
|
return index;
|
69
|
}
|
70
|
|
71
|
static void PrintIndex(IDictionary<String, TreeSet<int>> index)
|
72
|
{
|
73
|
foreach (String word in index.Keys)
|
74
|
{
|
75
|
Console.Write("{0}: ", word);
|
76
|
foreach (int ln in index[word])
|
77
|
Console.Write("{0} ", ln);
|
78
|
Console.WriteLine();
|
79
|
}
|
80
|
}
|
81
|
}
|
82
|
}
|