BotSharp/src/Infrastructure/BotSharp.Abstraction/Knowledges/Helpers/TextChopper.cs

66 lines
1.9 KiB
C#
Raw Normal View History

2023-06-29 23:14:57 +00:00
using System.Text.RegularExpressions;
2023-06-18 18:15:00 +00:00
2024-09-19 16:43:49 +00:00
namespace BotSharp.Abstraction.Knowledges.Helpers;
2023-06-18 18:15:00 +00:00
2024-08-31 06:05:53 +00:00
public static class TextChopper
2023-06-18 18:15:00 +00:00
{
2024-08-31 06:05:53 +00:00
public static List<string> Chop(string content, ChunkOption option)
2023-06-29 23:14:57 +00:00
{
content = Regex.Replace(content, @"\.{2,}", " ");
content = Regex.Replace(content, @"_{2,}", " ");
return option.SplitByWord ? ChopByWord(content, option) : ChopByChar(content, option);
}
2024-08-31 06:05:53 +00:00
private static List<string> ChopByWord(string content, ChunkOption option)
2023-06-29 23:14:57 +00:00
{
var chunks = new List<string>();
2024-09-19 16:43:49 +00:00
var words = content.Split(' ', StringSplitOptions.RemoveEmptyEntries).Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
2023-06-29 23:14:57 +00:00
2024-09-11 20:48:05 +00:00
var chunk = string.Empty;
2023-06-29 23:14:57 +00:00
for (int i = 0; i < words.Count; i++)
{
2024-09-19 16:43:49 +00:00
chunk += words[i];
2023-06-29 23:14:57 +00:00
if (chunk.Length > option.Size)
{
chunks.Add(chunk.Trim());
2024-09-11 20:48:05 +00:00
chunk = string.Empty;
2023-06-29 23:14:57 +00:00
i -= option.Conjunction;
}
2024-09-19 16:43:49 +00:00
else
{
chunk += " ";
}
2023-06-29 23:14:57 +00:00
}
2024-09-11 20:48:05 +00:00
if (chunks.IsNullOrEmpty() && !string.IsNullOrEmpty(chunk))
{
chunks.Add(chunk);
}
2023-06-29 23:14:57 +00:00
return chunks;
}
2024-08-31 06:05:53 +00:00
private static List<string> ChopByChar(string content, ChunkOption option)
2023-06-18 18:15:00 +00:00
{
var chunks = new List<string>();
2024-09-11 20:48:05 +00:00
var chunk = string.Empty;
2023-06-18 18:15:00 +00:00
var currentPos = 0;
2024-09-11 20:48:05 +00:00
2023-06-18 18:15:00 +00:00
while (currentPos < content.Length)
{
2024-09-11 20:48:05 +00:00
var len = content.Length - currentPos > option.Size ? option.Size : content.Length - currentPos;
chunk = content.Substring(currentPos, len);
2023-06-18 18:15:00 +00:00
chunks.Add(chunk);
// move backward
currentPos += option.Size - option.Conjunction;
}
2024-09-11 20:48:05 +00:00
if (chunks.IsNullOrEmpty() && !string.IsNullOrEmpty(chunk))
{
chunks.Add(chunk);
}
2023-06-18 18:15:00 +00:00
return chunks;
}
}