27

如何将文本拆分为单词?

示例文本:

“哦,你没办法,”猫说,“我们都疯了。我生气了。你疯了。'

该行中的单词是:

  1. 不能
  2. 帮助
  3. 全部
  4. 疯狂的
  5. 这里
  6. 我是
  7. 疯狂的
  8. 你是
  9. 疯狂的
4

7 回答 7

52

在空白处拆分文本,然后修剪标点符号。

var text = "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'";
var punctuation = text.Where(Char.IsPunctuation).Distinct().ToArray();
var words = text.Split().Select(x => x.Trim(punctuation));

完全同意例子。

于 2013-05-24T12:11:41.837 回答
26

首先,删除所有特殊字符:

var fixedInput = Regex.Replace(input, "[^a-zA-Z0-9% ._]", string.Empty);
// This regex doesn't support apostrophe so the extension method is better

然后拆分它:

var split = fixedInput.Split(' ');

对于删除特殊字符(您可以轻松更改)的更简单的 C# 解决方案,请添加此扩展方法(我添加了对撇号的支持):

public static string RemoveSpecialCharacters(this string str) {
   var sb = new StringBuilder();
   foreach (char c in str) {
      if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '\'' || c == ' ') {
         sb.Append(c);
      }
   }
   return sb.ToString();
}

然后像这样使用它:

var words = input.RemoveSpecialCharacters().Split(' ');

您会惊讶地发现这种扩展方法非常有效(肯定比 Regex 更有效),所以我建议您使用它;)

更新

我同意这是一种仅限英语的方法,但要使其与 Unicode 兼容,您所要做的就是替换:

(c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')

和:

char.IsLetter(c)

其中支持 Unicode,.Net 还为您提供char.IsSymbol各种char.IsLetterOrDigit情况

于 2013-05-24T00:06:11.000 回答
7

只是为了在@Adam Fridental 的答案上添加一个非常好的变体,你可以试试这个正则表达式:

var text = "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'";

var matches = Regex.Matches(text, @"\w+[^\s]*\w+|\w");

foreach (Match match in matches) {
    var word = match.Value;
}

我相信这是最短的正则表达式,可以得到所有的单词

\w+[^\s]*\w+|\w
于 2013-05-24T00:13:00.880 回答
1

如果您不想使用 Regex 对象,您可以执行类似...

string mystring="Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.";
List<string> words=mystring.Replace(",","").Replace(":","").Replace(".","").Split(" ").ToList();

您仍然需要处理“that,”末尾的尾随撇号

于 2013-05-24T03:21:44.293 回答
1

这是解决方案之一,我不使用任何辅助类或方法。

        public static List<string> ExtractChars(string inputString) {
            var result = new List<string>();
            int startIndex = -1;
            for (int i = 0; i < inputString.Length; i++) {
                var character = inputString[i];
                if ((character >= 'a' && character <= 'z') ||
                    (character >= 'A' && character <= 'Z')) {
                    if (startIndex == -1) {
                        startIndex = i;
                    }
                    if (i == inputString.Length - 1) {
                        result.Add(GetString(inputString, startIndex, i));
                    }
                    continue;
                }
                if (startIndex != -1) {
                    result.Add(GetString(inputString, startIndex, i - 1));
                    startIndex = -1;
                }
            }
            return result;
        }

        public static string GetString(string inputString, int startIndex, int endIndex) {
            string result = "";
            for (int i = startIndex; i <= endIndex; i++) {
                result += inputString[i];
            }
            return result;
        }
于 2015-04-24T08:45:38.677 回答
0

您可以尝试使用正则表达式删除不被字母(即单引号)包围的撇号,然后使用Char静态方法去除所有其他字符。通过首先调用正则表达式,您可以保留收缩撇号(例如can't),但删除单引号,如 in 'Oh

string myText = "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'";

Regex reg = new Regex("\b[\"']\b");
myText = reg.Replace(myText, "");

string[] listOfWords = RemoveCharacters(myText);

public string[] RemoveCharacters(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in input)
    {
        if (Char.IsLetter(c) || Char.IsWhiteSpace(c) || c == '\'')
           sb.Append(c);
    }

    return sb.ToString().Split(' ');
}
于 2013-05-24T00:28:45.397 回答
0

如果您想使用“for 循环”来检查每个字符并将所有标点符号保存 在输入字符串中,我已经创建了这个类。GetSplitSentence() 方法返回一个 SentenceSplitResult 列表。在此列表中,保存了所有单词和所有标点符号和数字。保存的每个标点符号或数字都是列表中的一个项目。sentenceSplitResult.isAWord 用于检查是否是一个单词。[对不起我的英语不好]

public class SentenceSplitResult
{
    public string word;
    public bool isAWord;
}

public class StringsHelper
{

    private readonly List<SentenceSplitResult> outputList = new List<SentenceSplitResult>();

    private readonly string input;

    public StringsHelper(string input)
    {
        this.input = input;
    }

    public List<SentenceSplitResult> GetSplitSentence()
    {
        StringBuilder sb = new StringBuilder();

        try
        {
            if (String.IsNullOrEmpty(input)) {
                Logger.Log(new ArgumentNullException(), "GetSplitSentence - input is null or empy");
                return outputList;                    
            }

            bool isAletter = IsAValidLetter(input[0]);

            // Each char i checked if is a part of a word.
            // If is YES > I can store the char for later
            // IF is NO > I Save the word (if exist) and then save the punctuation
            foreach (var _char in input)
            {
                isAletter = IsAValidLetter(_char);

                if (isAletter == true)
                {
                    sb.Append(_char);
                }
                else
                {
                    SaveWord(sb.ToString());
                    sb.Clear();
                    SaveANotWord(_char);                        
                }
            }

            SaveWord(sb.ToString());

        }
        catch (Exception ex)
        {
            Logger.Log(ex);
        }

        return outputList;

    }

    private static bool IsAValidLetter(char _char)
    {
        if ((Char.IsPunctuation(_char) == true) || (_char == ' ') || (Char.IsNumber(_char) == true))
        {
            return false;
        }
        return true;
    }

    private void SaveWord(string word)
    {
        if (String.IsNullOrEmpty(word) == false)
        {
            outputList.Add(new SentenceSplitResult()
            {
                isAWord = true,
                word = word
            });                
        }
    }

    private void SaveANotWord(char _char)
    {
        outputList.Add(new SentenceSplitResult()
        {
            isAWord = false,
            word = _char.ToString()
        });
    }
于 2019-06-18T21:57:03.763 回答