BotSharp/BotSharp.NLP/Corpus/FasttextDataReader.cs

53 lines
1.5 KiB
C#
Raw Normal View History

2018-09-09 01:47:53 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace BotSharp.NLP.Corpus
{
/// <summary>
/// Fasttext labeled data reader
/// </summary>
public class FasttextDataReader
{
public List<Sentence> Read(ReaderOptions options)
{
2018-09-09 03:59:01 +00:00
if (String.IsNullOrEmpty(options.LabelPrefix))
{
options.LabelPrefix = "__label__";
}
2018-09-09 01:47:53 +00:00
var sentences = new List<Sentence>();
using (StreamReader reader = new StreamReader(Path.Combine(options.DataDir, options.FileName)))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!String.IsNullOrEmpty(line))
{
2018-09-09 03:59:01 +00:00
var ms = Regex.Matches(line, options.LabelPrefix + @"\S+")
.Cast<Match>()
.ToList();
2018-09-09 01:47:53 +00:00
2018-09-09 03:59:01 +00:00
var text = line.Substring(ms.Last().Index + ms.Last().Length + 1);
ms.ForEach(m =>
2018-09-09 01:47:53 +00:00
{
2018-09-09 03:59:01 +00:00
sentences.Add(new Sentence
{
Label = m.Value.Substring(options.LabelPrefix.Length),
Text = text
});
2018-09-09 01:47:53 +00:00
});
2018-09-09 03:59:01 +00:00
2018-09-09 01:47:53 +00:00
}
}
}
return sentences;
}
}
}