我在一个字符串中有一个段落,我想得到该段落中的所有单词.
我的问题是我不希望后缀的单词以标点符号结尾,例如(',','.',''',''',';',':','!','? ')和/ n/t等
我也不希望用's和'这样的词world's来说它应该只返回世界.
在示例中
he said. "My dog's bone, toy, are missing!"
列表应该是: he said my dog bone toy are missing
Dan*_*Tao 26
根据Shan的回答,我会考虑这样的出发点:
MatchCollection matches = Regex.Match(input, @"\b[\w']*\b");
Run Code Online (Sandbox Code Playgroud)
为什么包括'角色?因为这会阻止像"我们"这样的单词被分成两个单词.捕获后,您可以自己手动删除后缀(否则,您无法识别这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;
}
Run Code Online (Sandbox Code Playgroud)
输入示例:
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]
这种方法的一个限制是它不能很好地处理首字母缩略词; 例如,"YMCA"将被视为四个单词.我认为,也可以通过包括处理.一个字符一个字匹配,然后剥离出来,如果它是一个句号之后(即,通过检查它的唯一的字以及最后一个字符周期).
| 归档时间: |
|
| 查看次数: |
21794 次 |
| 最近记录: |