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 81 82 83 84 85 86 87 88 89 90 91 92
|
public static class SubTitleParser
{
private static IEnumerable<string> GetSubTitleEnumerator(TextReader reader)
{
string line;
StringBuilder sb = new StringBuilder();
using (reader)
{
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line.Trim()))
{
yield return sb.ToString().TrimEnd();
sb = new StringBuilder();
}
else
{
sb.AppendLine(line);
}
}
if (sb.Length > 0)
yield return sb.ToString();
}
}
private static TextReader OpenSrt(string path)
{
return new StreamReader(File.OpenRead(path));
}
public static IEnumerable<SubTitleItem> Parse(string path)
{
TextReader reader = OpenSrt(path);
string[] delimiter = new string[1] { "-->" };
return (from subtitle in
(from title in GetSubTitleEnumerator(reader)
select title)
where string.IsNullOrEmpty(subtitle) == false
select new SubTitleItem(
int.Parse(subtitle.GetLine(0)),
ParseTime(subtitle.GetLine(1).Split(delimiter, StringSplitOptions.None)[0]),
ParseTime(subtitle.GetLine(1).Split(delimiter, StringSplitOptions.None)[1]),
subtitle.FromLineToEnd(2)));
}
private static TimeSpan ParseTime(string s)
{
TimeSpan result;
TimeSpan.TryParse(s.Replace(',', '.'), out result);
return result;
}
}
public class SubTitleItem
{
public SubTitleItem()
{ }
public SubTitleItem(int id, TimeSpan beginTime, TimeSpan endTime, string text)
{
Id = id;
BeginTime = beginTime;
EndTime = endTime;
Text = text;
}
public int Id { get; set; }
public TimeSpan BeginTime { get; set; }
public TimeSpan EndTime { get; set; }
public string Text { get; set; }
}
public static class stringExtension
{
public static string[] endLine = new string[1] { Environment.NewLine };
public static string GetLine(this string s, int index)
{
return s.Split(endLine, StringSplitOptions.None)[index];
}
public static string FromLineToEnd(this string s, int index)
{
return s.Split(endLine, StringSplitOptions.None)
.SkipWhile((a, b) => b < index).Aggregate((a, b) => a + b);
}
} |
Partager