【问题标题】:Count Number of Sentence Ruby计算句子的数量 Ruby
【发布时间】:2015-09-08 07:13:46
【问题描述】:

我碰巧到处搜索,但没有找到使用 Ruby 计算字符串中句子数量的解决方案。有谁怎么做?

例子

string = "The best things in an artist’s work are so much a matter of intuition, that there is much to be said for the point of view that would altogether discourage intellectual inquiry into artistic phenomena on the part of the artist. Intuitions are shy things and apt to disappear if looked into too closely. And there is undoubtedly a danger that too much knowledge and training may supplant the natural intuitive feeling of a student, leaving only a cold knowledge of the means of expression in its place. For the artist, if he has the right stuff in him ... "

这个字符串应该返回数字4

【问题讨论】:

标签: ruby count sentence


【解决方案1】:

您可以将文本拆分成句子并计算它们。这里:

string.scan(/[^\.!?]+[\.!?]/).map(&:strip).count # scan has regex to split string and strip will remove trailing spaces.
# => 4 

解释正则表达式:

[^\.!?]

字符类[^ ] 中的插入符号是否定运算符。这意味着我们正在寻找列表中不存在的字符:.!?

+

是一个贪心运算符,它返回 1 次到无限次之间的匹配。 (在这里捕捉我们的句子并忽略像...这样的重复)

[\.!?]  

匹配字符.!?

简而言之,我们正在捕获不是.!? 的所有字符,直到我们得到.!? 的字符。基本上可以看成一个句子(广义上)

【讨论】:

  • 要计算数组中的元素,这里实际上不需要.map(&:strip) :)
  • 你能解释一下你的正则表达式吗?它在做什么可能并不明显。
【解决方案2】:

我认为考虑一个单词 char 后跟一个 ?!. 作为句子的分隔符是有意义的:

string.strip.split(/\w[?!.]/).length
#=> 4

所以当... 像这样单独挂起时,我不会考虑将它作为分隔符:

  • “我等了一会儿……然后我就回家了”

不过话说回来,也许我应该……

我还想到,一个更好的分隔符可能是一个标点符号,后跟一些空格和一个大写字母:

string.split(/[?!.]\s+[A-Z]/).length
#=> 4

【讨论】:

  • 如果有需要的尤尔先生呢?
  • 您可以通过环视来解释这一点。不过,我会把它留给别人做练习。
【解决方案3】:

句子以句号、问号和感叹号结尾。他们也可以是 用破折号和其他标点符号分隔,但我们不会在这里担心这些罕见的情况。 拆分很简单。无需让 Ruby 将文本拆分为一种类型的字符,您只需 要求它拆分三种类型的字符中的任何一种,如下所示:

txt = "The best things in an artist’s work are so much a matter of intuition, that there is much to be said for the point of view that would altogether discourage intellectual inquiry into artistic phenomena on the part of the artist. Intuitions are shy things and apt to disappear if looked into too closely. And there is undoubtedly a danger that too much knowledge and training may supplant the natural intuitive feeling of a student, leaving only a cold knowledge of the means of expression in its place. For the artist, if he has the right stuff in him ... "

sentence_count = txt.split(/\.|\?|!/).length
puts sentence_count
#=> 7

【讨论】:

  • 它会产生一些额外的空行,对我来说计数是 7。
  • 是因为结尾有3个句号。
  • @Mourad 我已编辑您的答案并将返回值替换为实际值,即7
【解决方案4】:
string.squeeze('.!?').count('.!?')
  #=> 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多