我目前正在嘗試實作 changeAbbreviations 功能。我正在接收來自 .csv 的訊息,這些訊息被加載到一個名為 txtContent 的文本框中。示例訊息如下所示:
“嘿,剛剛聽了你的語音信箱,我是 ROFL,謝謝你的笑話”
我有一本字典,其中包含一個 textspeak 縮寫及其延長值的串列,我也在從 .csv 中讀取這些值,該 .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());
changeAbbreviations 函式:
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();
}
我希望我已經正確設定了這個問題,并感謝您的幫助:)
uj5u.com熱心網友回復:
我建議使用正則運算式和匹配而不是Split,這可以在我們有標點符號時幫助我們,例如
Call me ASAP!
正則運算式可以很好地提取"ASAP"我們可以從字典中替換的內容as soon as possible;當Split回傳{"Call", "me", "ASAP!"},我們的煩惱與"ASAP!"
代碼:
using System.Text.RegularExpressions;
...
//DONE:
// 1. ReadLines - we don't want premature materialization
// 2. Split(..2..) - no more then 2 items (in case text has commas)
private m_Dictionary = File
.ReadLines("textwords.csv")
.Select(x => x.Split(",", 2, StringSplitOptions.RemoveEmptyEntries | ))
.Where(pair => pair.Length == 2)
.ToDictionary(pair => pair[0], pair => pair[1]);
//DONE: business logic only, no UI
public string changeAbbreviations(string content,
IDictionary<string, string> dictionary = null) {
dictionary = dictionary ?? m_Dictionary;
if (string.IsNullOrEmpty(content))
return content;
// We try to change all uppercase words like ASAP, LOL etc.
return Regex.Replace(content, @"\p{Lu} ", match =>
dictionary.TryGetValue(match.Value, out var text)
? text
: match.Value);
}
// UI only
private void btnFilter_Click(object sender, RoutedEventArgs e) {
txtContentClean.Text = changeAbbreviations(txtContentClean.Text);
}
uj5u.com熱心網友回復:
試試這個
string content="LOL you are funny";
content = ChangeAbbreviations(content,dictionary);
結果
Laughing out loud you are funny
代碼
public string ChangeAbbreviations(string content, Dictionary<string, string> dictionary)
{
string pattern =@"[^0-9a-zA-Z:,] ";
string[] strArray = Regex.Split(content, pattern,
RegexOptions.IgnoreCase,
TimeSpan.FromMilliseconds(500));
for (var i=0; i < strArray.Length; i )
if ( dictionary.TryGetValue(strArray[i], out var wordFull))
strArray[i] = wordFull;
return string.Join(" ", strArray);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/381113.html
上一篇:在WPF中創建閃亮的顏色
