Rails 中的字数统计?
假设我有一个带有标题和正文的博客模型。如何显示正文中的字数和标题中的字符数?我希望输出是这样的
标题:Lorem 正文:Lorem Lorem Lorem
这篇文章的字数为 3。
Say I have a blog model with Title and Body. How I do show the number of words in Body and characters in Title? I want the output to be something like this
Title: Lorem
Body: Lorem Lorem Lorem
This post has word count of 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更新:如果您需要将摇滚乐作为一个单词进行匹配,您可以这样做
UPDATE: if you need to match rock-and-roll as one word, you could do like
还:
Also:
如果您对性能感兴趣,我编写了一个快速基准测试:
结果:
换句话说,
squish
对于 Very Large Strings™ 来说很慢。除此之外,split
速度更快(如果您不使用squish
,速度是两倍)。If you're interested in performance, I wrote a quick benchmark:
The results:
In other words,
squish
is slow with Very Large Strings™. Other than that,split
is faster (twice as fast if you're not usingsquish
).这里的答案有几个问题:
Joe's
将被视为两个单词Joe
和's
,这显然是不正确的。twenty-two
也是如此,它是一个复合词。这样的方法效果更好并解决了这些问题:
您可能需要查看我的字数统计宝石。它可以计算单词、单词的出现次数、长度以及其他一些内容。它也有很好的记录。
The answers here have a couple of issues:
Joe's
will be considered two wordsJoe
and's
which is obviously incorrect. As willtwenty-two
, which is a single compound word.Something like this works better and account for those issues:
You might want to look at my Words Counted gem. It allows to count words, their occurrences, lengths, and a couple of other things. It's also very well documented.
但正如我们所看到的,该句子只有 3 个单词。该问题与重音字符有关,因为正则表达式 \w 不将它们视为单词字符 [A-Za-z0-9_]。
改进的解决方案是
But as we can see, the sentence has only 3 words. The problem is related with the accented characters, because the regex \w doesn't consider them as a word character [A-Za-z0-9_].
An improved solution would be