我在单个字符串中有一个段落,我想获得该段落中的所有单词。如何获得在c#中的字符串的所有单词?
我的问题是,我不希望以(',','',''','',';',':','!等标点符号结尾的后缀单词。 ',‘?’)和/ N/T等
我也不想用的话年代和“M如world's
它应该只返回世界。
在这个例子中 he said. "My dog's bone, toy, are missing!"
该清单应该是:he said my dog bone toy are missing
我在单个字符串中有一个段落,我想获得该段落中的所有单词。如何获得在c#中的字符串的所有单词?
我的问题是,我不希望以(',','',''','',';',':','!等标点符号结尾的后缀单词。 ',‘?’)和/ N/T等
我也不想用的话年代和“M如world's
它应该只返回世界。
在这个例子中 he said. "My dog's bone, toy, are missing!"
该清单应该是:he said my dog bone toy are missing
扩展在Shan's answer,我会考虑这样的事情作为一个起点:
MatchCollection matches = Regex.Match(input, @"\b[\w']*\b");
为什么包括'
人物?因为这会阻止像“我们”这样的词被分成两个两个单词。捕获后,你可以自己手动去除后缀(否则,你不能识别re
是不是一个字,并忽略它)。
所以:
static string[] GetWords(string input)
{
MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b");
var words = from m in matches.Cast<Match>()
where !string.IsNullOrEmpty(m.Value)
select TrimSuffix(m.Value);
return words.ToArray();
}
static string TrimSuffix(string word)
{
int apostropheLocation = word.IndexOf('\'');
if (apostropheLocation != -1)
{
word = word.Substring(0, apostropheLocation);
}
return word;
}
示例输入:
he said. "My dog's bone, toy, are missing!" What're you doing tonight, by the way?
输出示例:
这种方法的[he, said, My, dog, bone, toy, are, missing, What, you, doing, tonight, by, the, way]
一个限制是,它不会处理缩写井;例如“Y.M.C.A.”将被视为四个字。我认为这也可以通过将.
作为一个字符匹配在一个单词中处理,然后剥离出来,如果它之后是一个句号(即,通过检查它是只有句号以及最后一个字符)。
请参阅Regex word boundary expressions,What is the most efficient way to count all of the words in a richtextbox?。故事的道德是有很多方法可以解决问题,但正则表达式可能是简单化的方法。
在空白处分割,修剪任何不是生成字符串中的字母的东西。
希望这是对你有帮助:
string[] separators = new string[] {",", ".", "!", "\'", " ", "\'s"};
string text = "My dog's bone, toy, are missing!";
foreach (string word in text.Split(separators, StringSplitOptions.RemoveEmptyEntries))
Console.WriteLine(word);
这里有一个循环替换方法......不是很快,但解决这个问题的方式......
string result = "string to cut ' stuff. ! out of";
".',[email protected]".ToCharArray().ToList().ForEach(a => result = result.Replace(a.ToString(),""));
这是假定你想将它放回原来的字符串,而不是新的字符串或列表。
你为什么要忽略狗`s`中的's`? – Justin 2011-02-11 15:07:37
难道你不能在白色字符上分割字符串,如空格,换行符和其他字符吗?两个空白之间的所有内容都是一个字... – Cipi 2011-02-11 15:09:53