【问题标题】:c# Convert string with Emoji to unicodec#将带有表情符号的字符串转换为unicode
【发布时间】:2018-08-28 18:12:27
【问题描述】:

我从客户端获取一个字符串,如下所示:

This is a face  :grin: 

我需要将 :grin: 转换为 unicode 以便将其发送到其他服务。

有什么办法吗?

【问题讨论】:

标签: c# unicode emoji


【解决方案1】:

这是一个link 到一个相当不错的 json 文件,其中包含相关信息。它包含带有表情符号的巨大数组(大约 1500 个条目),我们对 2 个属性感兴趣:“short_name”,它表示像“grin”这样的名称,以及“unified”属性,它包含像“1F601”这样的 unicode 表示。

我构建了一个帮助类来用它们的 unicode 等效项替换短名称,例如“:grin:”:

public static class EmojiParser {
    static readonly Dictionary<string, string> _colonedEmojis;
    static readonly Regex _colonedRegex;
    static EmojiParser() {
        // load mentioned json from somewhere
        var data = JArray.Parse(File.ReadAllText(@"C:\path\to\emoji.json"));
        _colonedEmojis = data.OfType<JObject>().ToDictionary(
            // key dictionary by coloned short names
            c => ":" + ((JValue)c["short_name"]).Value.ToString() + ":",
            c => {
                var unicodeRaw = ((JValue)c["unified"]).Value.ToString();
                var chars = new List<char>();
                // some characters are multibyte in UTF32, split them
                foreach (var point in unicodeRaw.Split('-'))
                {
                    // parse hex to 32-bit unsigned integer (UTF32)
                    uint unicodeInt = uint.Parse(point, System.Globalization.NumberStyles.HexNumber);
                    // convert to bytes and get chars with UTF32 encoding
                    chars.AddRange(Encoding.UTF32.GetChars(BitConverter.GetBytes(unicodeInt)));
                }
                // this is resulting emoji
                return new string(chars.ToArray());
            });
        // build huge regex (all 1500 emojies combined) by join all names with OR ("|")
        _colonedRegex =  new Regex(String.Join("|", _colonedEmojis.Keys.Select(Regex.Escape)));
    }

    public static string ReplaceColonNames(string input) {
        // replace match using dictoinary
        return _colonedRegex.Replace(input, match => _colonedEmojis[match.Value]);
    }
}

用法很明显:

var target = "This is a face&nbsp;&nbsp;:grin:&nbsp;:hash:";
target = EmojiParser.ReplaceColonNames(target);

它非常快(除了第一次运行,因为静态构造函数初始化)。在你的字符串上它需要不到 1 毫秒(无法用秒表测量,总是显示 0 毫秒)。在实践中你永远不会遇到的巨大字符串(1MB 的文本)上,在我的机器上需要 300 毫秒。

【讨论】:

  • 太棒了!!!!我在找什么。非常感谢您的支持
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 2015-01-15
  • 1970-01-01
  • 2016-10-22
  • 2021-10-04
相关资源
最近更新 更多