将句子分成单词,但在C#中使用标点符号有问题

时间:2011-09-05 18:46:15

标签: c# regex split words sentence

我已经看到了一些类似的问题,但我正在努力实现这一目标。

给定一个字符串,str =“月亮是我们的天然卫星,即它围绕地球旋转!” 我想提取单词并将它们存储在一个数组中。 预期的数组元素就是这个。

the 
moon 
is 
our 
natural 
satellite 
i.e. 
it  
rotates 
around 
the 
earth

我尝试使用String.split(','\ t','\ r'),但这不能正常工作。我也尝试删除。和其他标点符号,但我想要一个像“ie”的字符串也被解析出来了。实现这一目标的最佳方法是什么? 我也尝试使用regex.split无济于事。

string[] words = Regex.Split(line, @"\W+");

肯定会欣赏正确方向的一些推动。

4 个答案:

答案 0 :(得分:29)

正则表达式解决方案。

(\b[^\s]+\b)

如果确实希望修复.上的最后一个i.e.,您可以使用此功能。

((\b[^\s]+\b)((?<=\.\w).)?)

这是我正在使用的代码。

  var input = "The moon is our natural satellite, i.e. it rotates around the Earth!";
  var matches = Regex.Matches(input, @"((\b[^\s]+\b)((?<=\.\w).)?)");

  foreach(var match in matches)
  {
     Console.WriteLine(match);
  }

结果:

The
moon
is
our
natural
satellite
i.e.
it
rotates
around
the
Earth

答案 1 :(得分:8)

我怀疑你正在寻找的解决方案比你想象的要复杂得多。您正在寻找某种形式的实际语言分析,或者至少是字典,以便您可以确定句点是单词的一部分还是结束句子。你有没有考虑过它可以同时做到这两个事实?

考虑添加允许的“包含标点符号的单词”的字典。这可能是解决问题的最简单方法。

答案 2 :(得分:2)

这对我有用。

var str="The moon is our natural satellite, i.e. it rotates around the Earth!";
var a = str.Split(new char[] {' ', '\t'});
for (int i=0; i < a.Length; i++)
{
    Console.WriteLine(" -{0}", a[i]);
}

结果:

 -The
 -moon
 -is
 -our
 -natural
 -satellite,
 -i.e.
 -it
 -rotates
 -around
 -the
 -Earth!

你可以对结果进行一些后期处理,删除逗号和分号等。

答案 3 :(得分:1)

Regex.Matches(input, @"\b\w+\b").OfType<Match>().Select(m => m.Value)
相关问题