检查字符并将表情符号转换为文本? C#

时间:2014-04-29 01:47:32

标签: c# replace emoticons

我有像这样的数据库中的表情符号列表

id | emoticon | convert_text

1  |   :)     |  e_happy

2  |   :(     |  e_sad

如何检查表情符号列表中是否包含任何字符?

如果找到,则将表情符号更改为文本。

示例:

before
S = Smile at everyone who doesn't smile at your :)

after
S= Smile at everyone who doesn't smile at your e_happy

*被修改

首先,我试图像这样分开每个单词

static void Main(string[] args)
    {
        string value = "Smile at everyone who doesn't smile at your :)";
        char[] delimiter = new char[] { ' ', ',', '.' };

        string[] array = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
        foreach (string entry in array)
        {
            Console.WriteLine(entry);
        }
        Console.ReadKey();
    }

我很困惑如何用数据库中的表情符号列表检查每个单词,并将表情符号转换为文本,例如示例 *对不起,这是我的第一篇文章,我正在翻译谷歌翻译

2 个答案:

答案 0 :(得分:1)

由于表情符号的数量和符号可能非常大且非常随机( like :) ;) >:) @}-, etc; and then new can be added anytime ),我认为正则表达式不能用于所有表情符号。所以我想以更冗长的方式解决这个问题。

  1. 将所有表情符号加载到包含表情符号作为键的字典中,并将convert_text作为值加载(只需确保键不重复,否则会出现异常)
  2. 为每个表情符号键做一个foreach并在文本
  3. 中替换它

    声明字典

    Dictionary<string, string> emoticons = new Dictionary<string, string>();
    

    将表情符号加载到字典中(使用DataReader)

    // declare/open the connection (depends on the current application design
    
    string sql = "SELECT * FROM Emoticons
    // cmd.ExecuteReader above query to get dataReader (dr)
    
    while(dr.Read())
    {
        string key = dr.GetString(dr.GetOrdinal("Emoticons"));
    
        if(!emoticons.ContainsKey(key))
            emoticons.Add(key, dr.GetString(dr.GetOrdinal("convert_test"));
    }
    dr.Close();
    

    上面的字典可以存储为类级别对象或项目级别的全局对象,这样您就不必每次都读取数据库。

    用convert_text替换所有表情符号

    foreach(string key in emoticons.Keys)
       value = value.Replace(key, emoticons[key]);
    
    // here you will have all emoticons converted with their convert_text.
    

答案 1 :(得分:0)

如何使用正则表达式?

var emoticons = new Dictionary<string, string>
{
    { ":)" , "smile" },
    { ";)" , "blink" },
    { ">:)", "devil" },
    { "@}-", "rose"  }
};
string value = "Smile at everyone who doesn't smile at your :)";
Console.WriteLine(Regex.Replace(value, 
    String.Join("|",emoticons.Select(e => Regex.Escape(e.Key)).ToArray()), 
    (match) =>
    {
        string result = null;
        return emoticons.TryGetValue(match.Value, out result) 
            ? result : match.Value;
    }));

使用正则表达式,如果已经将它们正确地转义到数据库中,则可以使用相同的表达式匹配:):]。在此示例中,我认为所有表达式都是“不安全的”,因此我使用Regex.Escape调用