2015-11-05 70 views
0

我想忽略標點符號。因此,我試圖編寫一個程序來計算我的文本中每個單詞的所有出現,但沒有考慮標點符號。 所以我的計劃是:如何忽略標點符號c#

static void Main(string[] args) 
    { 
     string text = "This my world. World, world,THIS WORLD ! Is this - the world ."; 
     IDictionary<string, int> wordsCount = 
     new SortedDictionary<string, int>(); 
     text=text.ToLower(); 
     text = text.replaceAll("[^0-9a-zA-Z\text]", "X"); 
     string[] words = text.Split(' ',',','-','!','.'); 
     foreach (string word in words) 
     { 
      int count = 1; 
      if (wordsCount.ContainsKey(word)) 
       count = wordsCount[word] + 1; 
      wordsCount[word] = count; 
     } 

     var items = from pair in wordsCount 
        orderby pair.Value ascending 
        select pair; 

     foreach (var p in items) 
     { 
      Console.WriteLine("{0} -> {1}", p.Key, p.Value); 
     } 

    } 

輸出是:

is->1 
my->1 
the->1 
this->3 
world->5 
(here is nothing) -> 8 

我怎麼可以在這裏刪除標點?

+3

使用'text.Split(新[] {」 「」 「,」 - 「,」!「,」。「},StringSplitOptions.RemoveEmptyEntries);'排除空的條目。 – Kvam

回答

1

你應該嘗試指定StringSplitOptions.RemoveEmptyEntries

string[] words = text.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 

注意,不是所有的標點字符手動創建char[],你可以創建一個string並調用ToCharArray()獲得字符數組。

我發現以後更容易閱讀和修改。

0

這很簡單 - 第一步是用功能Replace刪除不需要的標點符號,然後按照您的要求繼續拆分。

1
string[] words = text.Split(new char[]{' ',',','-','!','.'}, StringSplitOPtions.RemoveEmptyItems); 
+2

那個不編譯。你需要'new char [] {...}'版本。 – LarsTech

+0

thx - 固定.... – pm100

0

...你可以與製作人去哭版本...

"This my world. World, world,THIS WORLD ! Is this - the world ." 
    .ToLower() 
    .Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
    .GroupBy(i => i) 
    .Select(i=>new{Word=i.Key, Count = i.Count()}) 
    .OrderBy(k => k.Count) 
    .ToList() 
    .ForEach(Console.WriteLine); 

..輸出

{ Word = my, Count = 1 } 
{ Word = is, Count = 1 } 
{ Word = the, Count = 1 } 
{ Word = this, Count = 3 } 
{ Word = world, Count = 5 }