【问题标题】:Ruby Text Parsing: Find the start of the next sentenceRuby 文本解析:找到下一个句子的开头
【发布时间】:2012-09-10 10:24:49
【问题描述】:

我的数据库中有一堆这样的字符串:

下班开车回家。狗从沙发上一跃而起 师傅在门口。他把脸舔干净了。

字符串从句子的中间开始。我想找到一种方法来切断最初不完整的句子,然后从“狗从沙发上跳下来到门口的伟大主人那里。他把脸舔干净了。”

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby text string-parsing


    【解决方案1】:

    最简单的答案:

    str = 'driving home from work. The dog leaped of the sofa to great his master at the door. He licked his face clean.'
    str.sub!(/^[^A-Z].+?\./, '').strip!
    

    【讨论】:

    • 这将删除第一句,不管...并留下一个空白。
    • 现已修复。仅当文本不以大写开头到下一个点时才会删除。 strip! 也将删除所有开头和后面的空格。
    • 我喜欢,简单,好记。它会处理首句以数字、符号等开头的情况。
    【解决方案2】:

    可能是这样的吗?

    str = "driving home from work. The dog leaped of the sofa to great his master at the door. He licked his face clean."
    str.first == str.first.upcase ? str : str.split(".")[1..-1].join(".").lstrip << "."
    

    假设它以大写字母开头表示句子的开头,否则不可能。其他要考虑的情况,如果它以数字开头怎么办?例如:1 条狗跑掉了。狗……是1狗……一句话?

    【讨论】:

      【解决方案3】:

      https://github.com/ged/linkparser

      这可能会有所帮助。

      【讨论】:

        【解决方案4】:

        问题是如何定义不完整的句子。我们可以假设所有以大写字符开头的句子都是完整的句子。如果是这样,代码可能如下所示

        str = 'driving home from work. The dog leaped of the sofa to great his master at the door. He licked his face clean.'
        sentences = str.split('.')
        sentences.shift if sentences[0][0].downcase == sentences[0][0]
        sentences.join('.').strip << '.'
        

        有点棘手,但有效。

        【讨论】:

          猜你喜欢
          • 2010-10-26
          • 1970-01-01
          • 2021-09-20
          • 2011-05-21
          • 2017-06-02
          • 1970-01-01
          • 2014-07-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多