红宝石句数

依康汤

我碰巧到处搜索,但没有找到使用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 ... "

该字符串应返回number 4

湿婆

您可以将文本拆分为句子并计数。这里:

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

解释正则表达式:

[^\.!?]

字符类内部的插入号[^ ]是取反运算符。这意味着我们正在寻找这是不存在的名单字符:.!?

+

是一个贪婪的运算符,返回1到无限次之间的匹配项。(在此处捕获我们的句子,而忽略类似的重复...

[\.!?]  

匹配的字符.!?

简单地说,我们正在捕捉是不是所有的字符.!?直到我们得到的是字符.!?基本上可以将其视为句子(广义上)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章