如何将文字拆分成文字?

时间:2013-05-24 00:03:47

标签: c# .net

如何将文字拆分成文字?

示例文字:

  “哦,你无能为力,”猫说:“我们都疯了。我生气了。你生气了。'

该行中的文字是:

  1. 不能
  2. 帮助
  3. 所述
  4. 我们
  5. 所有
  6. 这里
  7. 您是

7 个答案:

答案 0 :(得分:36)

在空格上拆分文字,然后修剪标点符号。

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));

完全赞同例子。

答案 1 :(得分:23)

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

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(' ');

你会惊讶地知道这种扩展方法非常有效(肯定比正则表达式更有效)所以我建议你使用它;)

<强>更新

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

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

使用:

char.IsLetter(c)

哪个支持Unicode,。。还为各种案例提供char.IsSymbolchar.IsLetterOrDigit

答案 2 :(得分:6)

只是为@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;
}

我相信这是最短的RegEx,可以获得所有的单词

\w+[^\s]*\w+|\w

答案 3 :(得分: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();

你仍然需要在“那个”

的末尾处理尾随撇号

答案 4 :(得分: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;
        }

答案 5 :(得分:0)

您可以尝试使用正则表达式删除未被字母(即单引号)包围的撇号,然后使用Char静态方法去除所有其他字符。通过首先调用正则表达式,您可以保留缩减撇号(例如can't),但删除'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(' ');
}

答案 6 :(得分:0)

如果要使用“ for cycle”检查每个字符并在输入字符串中保存所有标点符号,我已经创建了此类。方法GetSplitSentence()返回SentenceSplitResult的列表。在此列表中,保存了所有单词以及所有标点符号和数字。保存的每个标点符号或数字都是列表中的一项。句子SplitResult.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()
        });
    }