如何忽略标点符号c#
本文关键字:标点符号 何忽略 | 更新日期: 2023-09-27 18:20:48
我想忽略标点符号。因此,我正试图制作一个程序,统计文本中每个单词的所有外观,但不考虑标点符号。所以我的程序是:
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
如何删除此处的标点符号?
您应该尝试指定StringSplitOptions.RemoveEmptyEntries
:
string[] words = text.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
请注意,您可以创建一个string
并调用ToCharArray()
来获取字符数组,而不是手动创建一个包含所有标点符号的char[]
。
我发现以后更容易阅读和修改。
string[] words = text.Split(new char[]{' ',',','-','!','.'}, StringSplitOPtions.RemoveEmptyItems);
这很简单-第一步是使用函数Replace
删除不需要的标点符号,然后继续进行拆分。
。。。你可以选择让人哭的版本。。。
"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 }