2014-01-11 85 views
-2

UPDATE計數重複的單詞/句子

對不起,我有一點英語。

我想對字符串中的短語進行計數。

我的字符串在下面;

Lorem存有悲阿梅德,consectetur adipiscing ELIT。法無 venenatis,Lorem存有 augue德維爾pellentesque 坐阿梅德Lorem存有悲拉克絲egestas, 等存有悲法無。

我想在下面;

  • 3倍Lorem存有

  • 2X 坐阿梅德

+0

發佈您嘗試過的代碼可能會讓其他人建議更好的方法(而不是浪費時間建議您嘗試並丟棄的方法)或改進您的功能。然而,我認爲一個正則表達式和計數匹配的次數應該可以正常工作。 – Tim

+0

我更新了問題。 – user3186216

+0

你是否提前知道你在找什麼短語?或者你是否需要邏輯來查出每個可能的多字詞?如果是後者,最多是兩個字嗎?最小值是多少? – erikrunia

回答

1

第一,它不是很清楚你所說的 「重複的話」 的意思,但我」猜測你需要將逗號分隔的單詞或短語列表拆分爲單個單詞,並對每個單詞進行測試WN。如果多數民衆贊成的情況下:

string words = "I love red color. He loves red color. She love red kit. "; 
myWordString = myWordString .Replace(" ", ","); 
myWordString = myWordString .Replace(".", ""); 

string[] words = s.Split(','); 
foreach (string theWord in words) 
{ 
    // now do something with them individually 
} 

使用字典

Dictionary<string, Int32> wordList= new Dictionary<string, Int32>(); 

那麼一旦您完成在串詞取詞串,循環,並在每個循環中,您可以添加到字典,或增加計數

-- psuedo loop code from above 

if (wordList.ContainsKey(theWord)) { 

    wordList[theWord] = wordList[theWord] + 1; 

} else { 

    wordList.Add(theWord, 1); 

} 

-- end psuedo loop code from above 

等等等等。當你的循環完成通過你的列表中的所有單詞去..你可以去翻翻字典,像這樣:

foreach(var pair in wordList) 
{ 
    var key = pair.Key; 
    var value = pair.Value; 
} 
+0

謝謝。我更新了我的問題。 – user3186216

0

有關使用LINQ如何?

var wordList = words.Split(new[] { " ", ".", "," }, StringSplitOptions.RemoveEmptyEntries) 
        .GroupBy(x => x) 
        .ToDictionary(g => g.Key, g => g.Count()); 
+0

謝謝。我嘗試過但包含了一個詞,例如「lorem」。我想「lorem ipsum」。 – user3186216