使用regex c#将tweet中的emoticon替换为word
本文关键字:emoticon 替换 word 中的 tweet regex 使用 | 更新日期: 2023-09-27 18:18:24
基本思路是将字符串中的表情符号映射到实际单词。说for:)你用happy代替它。一个更明显的例子是。原:今天是一个晴朗的日子:)。但是明天要下雨了。最后:今天是一个阳光明媚的日子。但是明天会下大雨。
我尝试了一个解决方案,使用一个共同的正则表达式为所有的表情符号,但我不确定一旦你检测到它是一个表情符号,如何回去,并用适当的词替换每一个。我只需要三个表情符号:),:)和:D。谢谢你。
使用一个自定义匹配求值器的Regex.Replace
方法
static string ReplaceSmile(Match m) {
string x = m.ToString();
if (x.Equals(":)")) {
return "happy";
} else if (x.Equals(":(")) {
return "sad";
}
return x;
}
static void Main() {
string text = "Today is a sunny day :). But tomorrow it is going to rain :(";
Regex rx = new Regex(@":[()]");
string result = rx.Replace(text, new MatchEvaluator(ReplaceSmile));
System.Console.WriteLine("result=[" + result + "]");
}
为什么不使用普通替换呢?你只有三个固定的模式:
str = str.Replace(":(", "text1")
.Replace(":)", "text2")
.Replace(":D", "text3")
更一般的解决方案:
var emoticons = new Dictionary<string, string>{ {":)", "happy"}, {":(", "sad"} };
string result = ":) bla :(";
foreach (var emoticon in emoticons)
{
result = result.Replace(emoticon.Key, emoticon.Value);
}
对于任何需要替换的其他表情符号,只需在字典中添加另一个键值对,如{":D", "laughing"}
。
作为foreach-loop的替代方法,也可以(尽管不一定推荐)使用Aggregate
标准查询操作符:
string result = emoticons.Aggregate(":) bla :(",
(text, emoticon) => text.Replace(emoticon.Key, emoticon.Value));
为什么是regex?
string newTweet = oldTweet
.Replace(":)","happy")
.Replace(":(","sad")
.Replace(":D","even more happy");