Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Tokenizer Helper class to ERNIE-Bot.SDK #61

Merged
merged 3 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/ERNIE-Bot.SDK/Tokenizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ERNIE_Bot.SDK
{
/// <summary>
/// This class provides methods for tokenizing text.
/// </summary>
public static class Tokenizer
{
public static int ApproxNumTokens(string text)
{
int chinese = Regex.Matches(text, @"\p{IsCJKUnifiedIdeographs}").Count;
int english = Regex.Replace(text, @"[^\p{IsBasicLatin}-]", " ")
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Count(w => !string.IsNullOrWhiteSpace(w) && w != "-" && w != "_");

return chinese + (int)Math.Floor(english * 1.3);
}
}
}
16 changes: 16 additions & 0 deletions tests/ERNIE-Bot.SDK.Tests/TokenizerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using ERNIE_Bot.SDK;

namespace ERNIE_Bot.SDK.Tests
{
public class TokenizerTests
{
[Fact]
public void TestApproxNumTokens()
{
string text = "这是一段测试文字This is a test string.";
int expected = 14;
int actual = Tokenizer.ApproxNumTokens(text);
Assert.Equal(expected, actual);
}
}
}