2013-11-21 77 views
0
public void replaceText(string messageText) 
    { 
     int counter = 1; 
     string csvFile = "textwords.csv"; 
     string[] words = messageText.Split(' '); 
     char csvSeparator = ','; 

     foreach (string word in words) 
     { 
      foreach (string line in File.ReadLines(csvFile)) 
      { 
       foreach (string value in line.Replace("\"", "").Split('\r', '\n',  csvSeparator)) 
        if (value.Trim() == word.Trim()) // case sensitive  
        { 
         messageText = Regex.Replace(messageText, value, string.Empty); 

         messageText = messageText.Insert(counter, " " + line); 

        } 
      } 
      counter++; 
     } 
     MessageBox.Show(messageText); 
    } 

因此,我有上面的代碼,它會搜索我的CSV文件以匹配messageText中的每個單詞。 CSV文件包含textspeak縮寫,並且每次找到匹配項時,都會將messageText中的單詞替換爲找到的單詞。例如,「hi LOL」會在CSV中發現「LOL,笑出聲來」,並將其替換爲用CSV中的匹配替換單詞

但是,這隻適用於一個替換。如果我輸入「Hi LOL」,它會輸出「Hi LOL,大聲笑」

但是如果我把「Hi LOL,你好嗎?LMAO」輸出「Hi LOL LMFAO,笑我A ** , 你好嗎?」

誰能告訴我,我要去哪裏錯了,我想不通爲什麼它是這樣做的

+1

我不能讓我的周圍是什麼,這是應該做的頭,但在我看來它有點匪夷所思從文件中讀取整個字典中的每個字該消息,並且您不應該使用Regex.Replace進行簡單的文本替換,並且如果您使用替換函數,則不需要單獨執行「插入」。 –

+1

您應該編輯您的問題以清楚地顯示輸入消息,.CSV文件的內容和輸出錯誤。 –

+0

你是對的,一直在這工作了一段時間,所以我很累 改變它只是 messageText = Regex.Replace(messageText,word,line); –

回答

0

有一些問題用這種方法: 1需要2個職責(負載鍵/值對從csv文件並替換文字)。每次調用時,csv文件都會被加載。 2變量'counter'對於該方法而言看起來很奇怪。

這裏是重寫代碼:

static void Main(string[] args) { 
     var dictionary = LoadFromFile("c:\textWords.csv"); 
     var message = "Hi LOL, LMAO"; 
     message = ReplaceMessage(message, dictionary); 
     // 
    } 

    static Dictionary<String, String> LoadFromFile(String csvFile) { 
     var dictionary = new Dictionary<String, String>(); 
     var lines = File.ReadAllLines(csvFile); 
     foreach (var line in lines) { 
      var fields = line.Split(',', '\r', '\n'); 
      dictionary[fields[0].Trim()] = fields[1].Trim(); 
     } 
     return dictionary; 
    } 

    static String ReplaceMessage(String message, Dictionary<String, String> dictionary) { 
     var words = message.Split(' ', ','); 
     var s = new StringBuilder(); 
     foreach (var word in words) { 
      if (dictionary[word] != null) { 
       s.Append(String.Format("{0}, {1} ", word, dictionary[word])); 
      } else { 
       s.Append(word + " "); 
      } 
     } 
     return s.ToString().TrimEnd(' '); 
    }