【发布时间】:2022-01-15 20:04:18
【问题描述】:
我目前正在尝试实现一个 changeAbbreviations 函数。我正在接收来自 .csv 的消息,这些消息被加载到名为 txtContent 的文本框中。示例消息如下所示:
“嘿,刚刚听到你的语音邮件,我是 ROFL,谢谢你的笑话”
我有一个字典,其中包含一个 textspeak 缩写列表及其延长值,我还从一个 .csv 中读取,其结构如下:
ROFL,笑着在地上打滚
大声笑,大声笑
AFK,远离键盘
BRB,马上回来
等等
我要实现的是,在按钮单击事件上,该函数将被调用,用拉长的值替换缩写并将新消息推送到名为 txtContentClean 的文本框
该函数将遍历字符串中的每个单词,如果单词与字典键之一匹配,它将用值替换它。
我不太确定如何进行,并希望有人能够向我展示如何正确实现这一点。到目前为止,我已经在下面复制了我的代码:
字典:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Dictionary<string, string> dictionary = File.ReadAllLines("textwords.csv").Select(x =>
x.Split(",", StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(key => key.FirstOrDefault().Trim(),
value => value.Skip(1).FirstOrDefault().Trim());
更改缩写功能:
public void changeAbbreviations(string content, Dictionary<string, string> dictionary)
{
var abbreviations = new List<string>();
foreach (string word in content.Split(' '))
{
bool wordExists = dictionary.ContainsKey(word);
if (wordExists)
{
abbreviations.Add(word);
}
}
foreach (string word in abbreviations)
{
content.Replace(word, dictionary[word]);
}
txtContentClean.Text = content;
}
按钮事件:
private void btnFilter_Click(object sender, RoutedEventArgs e)
{
changeAbbreviations();
}
我希望我已经正确设置了这个问题,并感谢您的任何帮助:)
【问题讨论】:
-
您也必须发布 textwords.csv 的一部分,以便我们进行测试
-
你还需要
content = content.Replace(word, dictionary[word];,因为Replace不修改原始字符串,它返回修改后的字符串。如果有很多替换项,我建议使用 StringBuilder 代替content作为字符串 -
是否需要考虑大小写变化,比如“rofl”?
标签: c# wpf dictionary