【问题标题】:LINQ split string into sentences dependently to quotesLINQ 根据引号将字符串拆分为句子
【发布时间】:2016-01-28 08:06:32
【问题描述】:

如何将文本拆分为文本中的句子;带点、问号、感叹号等。我试图一个接一个地得到每个句子,除了引号内。

例如拆分这个:

Walked. Turned back. But why? And said "Hello world. Damn this string splitting things!" without a shame.

像这样:

Walked. 
Turned back. 
But why? 
And said "Hello world. Damn this string splitting things!" without a shame.

我正在使用此代码:

 private List<String> FindSentencesWhichContainsWord(string text, string word)
        {
            string[] sentences = text.Split(new char[] { '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries);

            // Define the search terms. This list could also be dynamically populated at runtime.
            string[] wordsToMatch = { word };

            // Find sentences that contain all the terms in the wordsToMatch array.
            // Note that the number of terms to match is not specified at compile time.
            var sentenceQuery = from sentence in sentences
                                let w = sentence.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
                                                        StringSplitOptions.RemoveEmptyEntries)
                                where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count()
                                select sentence;

            // Execute the query. Note that you can explicitly type
            // the iteration variable here even though sentenceQuery
            // was implicitly typed. 

            List<String> rtn = new List<string>();
            foreach (string str in sentenceQuery)
            {
                rtn.Add(str);
            }
            return rtn;
        }

但它给出的结果不是我想要的。

Walked. 
Turned back. 
But why? 
And said "Hello world.
Damn this string splitting things!
" without a shame.

【问题讨论】:

  • 您的Split 数组中有'!' 字符
  • 你可以测试你的字符串,如果点、感叹号等在引号内,然后跳过分割函数。

标签: c# linq text


【解决方案1】:

我觉得这个问题可以分两步解决:

  1. 使用TextFieldParser正确识别引用词

    string str = "Walked. Turned back. But why? And said \"Hello world. Damn this string splitting things!\" without a shame.";
    string[] words = null;
    using (TextFieldParser parser = new TextFieldParser(new StringReader(str))){
        parser.Delimiters = new string[] { " " };
        parser.HasFieldsEnclosedInQuotes = true;
        words = parser.ReadFields();                
    }    
    
  2. 根据您想要的特殊行为,使用较早的结果自定义 string 的新数组。

    List<string> newWords = new List<string>();
    string accWord = "";
    foreach (string word in words) {
        if (word.Contains(" ")) //means this is multiple items
            accWord += (accWord.Length > 0 ? " " : "") + "\"" + word + "\"";
        else {
            accWord += (accWord.Length > 0 ? " " : "") + word;
            if (word.EndsWith(".") || word.EndsWith("!") || word.EndsWith("?")) {
                newWords.Add(accWord);
                accWord = "";
            }
        }
    }
    

结果newWords:

[2016-01-28 08:29:48.534 UTC] Walked.
[2016-01-28 08:29:48.536 UTC] Turned back.
[2016-01-28 08:29:48.536 UTC] But why?
[2016-01-28 08:29:48.536 UTC] And said "Hello world. Damn this string splitting things!" without a shame.

如果需要,您可以简单地将这两个包装在一个返回 List&lt;string&gt; 的方法中

【讨论】:

  • 这很有趣。我还不知道TextFieldParser。
  • @t3chb0t 它在Microsoft.VisualBasic.FileIO namespace 中。通常用于实际处理 CSV 文件。 :) 看看!
  • @ErtürkÖztürk 它通常用于 CSV 文件,但您可以根据需要更改分隔符。关于它的一件最好的事情是它可以识别引号! :) 在我的示例中,在第一部分中,我将文本拆分为space。并且所有单词都将被空格分隔除了引号中的单词。然后在我的第二部分中,我再次重新排列了单词。 :) 您可以在上面的示例中打印words 以检查TextFieldParser 的实际工作方式。然后你会得到更清晰的画面...... :)
  • @Ian 在我尝试在我的代码上实现它之后,我发现这不是我真正想要的,因为用空格分隔不是一个好的起点,因为文本和标点符号的使用并不完美,实际上通常它真的远非完美。所以我不认为这对我来说是最好的解决方案。是的,它有效,但仅适用于标准条件。
  • @ErtürkÖztürk 这听起来很糟糕...... :( 但也许你可以提供更多的输入输出样本?我认为,如果有任何真实案例,我们只能考虑合适的解决方案。我给您的解决方案仅适用于给定的示例 - 确实,我并不完全知道您将如何使用它。
【解决方案2】:

您正在寻找一种叫做“分句器”的东西。这不是一个小问题...

如果您对如何正确解决这类问题感兴趣,我会推荐 Manning 和 Schutze 的《统计自然语言处理基础》一书。

为了让您了解这有多复杂,我将简要描述我们在 Nubilosoft 使用的句子拆分器,作为我们搜索组件的一部分。

  • 首先我们进行段落拆分。通过这样做,我们消除了一些明显的错误,并使我们的文本更小。大多数文件格式(如 MS Word DOC(X) 和 HTML)已经提供了段落标记,这是很好的第一步。
  • 接下来,我们对文本进行特征提取。特征是诸如标点符号、一些常见的缩写(如“博士”)和一些上下文信息。
  • 我们确定分割点。分割点是改变大小写的标点和字符。 (人们有时会忘记标点符号)。
  • 最后,我们将其全部输入到感知器神经网络中,然后由感知器神经网络确定某物是否是“分割”位置。

这里的所有内容都是在手动注释的语料库上训练和测试的;具体的数字我记不得了,但是句子挺多的。

通过这样做,它的正确率大约为 99%,这对于我们的目的来说“已经足够好”了。

请注意,语料库的许可是一项相当棘手的业务...过去,我发现让自己成为一个正常工作的句子拆分器的最简单方法是简单地购买一个已经训练过的。

【讨论】:

  • 除了第二步和第四步外,我正在尝试按照与您的演练相同的方式进行操作,但是单独执行此操作已经足够复杂,并且在我的情况下为此付出努力值得怀疑。我正在尝试获取文本中的所有句子并使操作员可以一一选择单词,这些选择将提供给应用程序。感谢您提供详细信息。我很高兴听到这个话题足够深入,可以使其系统化。顺便说一句,我怀疑这本书是否是多语言的。
  • @ErtürkÖztürk 我们拥有用于十多种语言的大多数 NLP 工具。大多数语言的统计数据是相似的,但您确实需要为每种语言制定不同的规则,例如标记、缩写等。本书描述的是基础,而不是实现细节。 PS:分词叫做tokenization,也是比较有挑战性的。
【解决方案3】:

我使用了 TakeWhile。直到字符不是分隔符为止。或者如果它在引号内。

var seperator = new[] {'.', '?', '!'};

string str =
    @"Walked. Turned back. But why? And said ""Hello world. Damn this string splitting things!"" without a shame.";

List<string> result = new List<string>();
int index = 0;
bool quotes = false;
while (index < str.Length)
{
    var word = str.Skip(index).TakeWhile(ch =>
    {
        index++;
        if (ch == '"') quotes = !quotes;
        return quotes || !seperator.Contains(ch);
    });

    result.Add(string.Join("", word).Trim());
}

【讨论】:

  • 输出为:Walked Turned back But why And said "Hello world. Damn this string splitting things!" without a shame
  • 感谢您的回答,这是我见过的最短的方法,但它没有在句末使用标点符号。好吧,我可以再写一封信,但也许有更简单的解决方法。
  • 这种方式不是完整的解决方案,我不能接受对不起。我会另辟蹊径。
【解决方案4】:

这不是一个防弹解决方案,但它可以像这样实现。我手动做了句子和引号识别

void Main()
{
    var text = "Walked. Turned back. But why? And said \"Hello world. Damn this string splitting things!\" without a shame.";
    var result = SplitText(text);
}

private static List<String> SplitText(string text)
{
    var result = new List<string>();

    var sentenceEndings = new HashSet<char> { '.', '?', '!' };

    var startIndex = 0;
    var length = 0;

    var isQuote = false;
    for (var i = 0; i < text.Length; i++)
    {
        var c = text[i];
        if (c == '"' && !isQuote)
        {
            isQuote = true;
            continue;
        }

        if (c == '"' && isQuote)
        {
            isQuote = false;
            continue;
        }

        if (!isQuote && sentenceEndings.Contains(c))
        {
            length = i + 1 - startIndex;
            var part = text.Substring(startIndex, length);
            result.Add(part);
            startIndex = i + 2;
        }
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多