-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNgramGenerator.cs
80 lines (69 loc) · 2.55 KB
/
NgramGenerator.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.Text;
namespace LogEntryClustering
{
/// <summary>
/// Given list of token generates string compositions (ngrams) then hashes and return ngrams.
/// Different implementation can return different number of ngram hashes
/// </summary>
public interface INgramGeneratorAndHasher
{
ImmutableArray<int> Generate(in ReadOnlySpan<string> tokens);
}
class TokenShinglesNgramGeneratorAndHasher : INgramGeneratorAndHasher
{
private readonly int tokensInShingle;
public TokenShinglesNgramGeneratorAndHasher(int tokensInShingle)
{
this.tokensInShingle = tokensInShingle;
}
ImmutableArray<int> INgramGeneratorAndHasher.Generate(in ReadOnlySpan<string> tokens)
{
if (tokens.Length < tokensInShingle)
// don't take into account incomplete tails
return ImmutableArray<int>.Empty;
var s = new StringBuilder();
for (var i = 0; i < tokensInShingle; i++)
{
var token = tokens[i];
s.Append(token);
}
return new ImmutableArray<int> {s.ToString().GetHashCode()};
}
}
class TokenMaskingNgramGeneratorAndHasher : INgramGeneratorAndHasher
{
private readonly int ngramLength;
private readonly int numberOfMaskedOut;
public TokenMaskingNgramGeneratorAndHasher(int ngramLength, int numberOfMaskedOut)
{
this.ngramLength = ngramLength;
this.numberOfMaskedOut = numberOfMaskedOut;
}
ImmutableArray<int> INgramGeneratorAndHasher.Generate(in ReadOnlySpan<string> tokens)
{
if (tokens.Length < ngramLength)
// don't take into account incomplete tails
return ImmutableArray<int>.Empty;
var result = new List<int>();
for (int maskPos = 0; maskPos < ngramLength; maskPos++)
{
var s = new StringBuilder();
for (var i = 0; i < ngramLength; i++)
{
if (i - maskPos == 0 || i - maskPos == numberOfMaskedOut-1)
{
var token = tokens[i];
s.Append(token);
}
}
result.Add(s.ToString().GetHashCode());
}
return result.ToImmutableArray();
}
}
}