2015-11-05 142 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 }