如何忽略标点符号c#

时间:2015-11-05 17:57:21

标签: 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

如何删除标点符号?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您应该尝试指定StringSplitOptions.RemoveEmptyEntries

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

请注意,您可以创建char[]并调用string来获取字符数组,而不是手动创建包含所有标点字符的ToCharArray()

我发现以后更容易阅读和修改。

答案 2 :(得分:0)

这很简单 - 第一步是删除功能Replace的不需要的标点符号,然后继续分割。

答案 3 :(得分: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 }