假设我有一个标题和正文的博客模型。我如何显示Body中的单词数和Title中的字符数?我希望输出是这样的
标题:Lorem 身体:Lorem Lorem Lorem
此帖子的字数为3。
答案 0 :(得分:34)
"Lorem Lorem Lorem".scan(/\w+/).size
=> 3
更新:如果你需要将摇滚乐作为一个单词匹配,你可以这样做
"Lorem Lorem Lorem rock-and-roll".scan(/[\w-]+/).size
=> 4
答案 1 :(得分:17)
此外:
"Lorem Lorem Lorem".split.size
=> 3
答案 2 :(得分:4)
如果你对表现感兴趣,我写了一个快速的基准:
require 'benchmark'
require 'bigdecimal/math'
require 'active_support/core_ext/string/filters'
# Where "shakespeare" is the full text of The Complete Works of William Shakespeare...
puts 'Benchmarking shakespeare.scan(/\w+/).size x50'
puts Benchmark.measure { 50.times { shakespeare.scan(/\w+/).size } }
puts 'Benchmarking shakespeare.squish.scan(/\w+/).size x50'
puts Benchmark.measure { 50.times { shakespeare.squish.scan(/\w+/).size } }
puts 'Benchmarking shakespeare.split.size x50'
puts Benchmark.measure { 50.times { shakespeare.split.size } }
puts 'Benchmarking shakespeare.squish.split.size x50'
puts Benchmark.measure { 50.times { shakespeare.squish.split.size } }
结果:
Benchmarking shakespeare.scan(/\w+/).size x50
13.980000 0.240000 14.220000 ( 14.234612)
Benchmarking shakespeare.squish.scan(/\w+/).size x50
40.850000 0.270000 41.120000 ( 41.109643)
Benchmarking shakespeare.split.size x50
5.820000 0.210000 6.030000 ( 6.028998)
Benchmarking shakespeare.squish.split.size x50
31.000000 0.260000 31.260000 ( 31.268706)
换句话说,使用Very Large Strings™,squish
速度很慢。除此之外,split
更快(如果您不使用squish
,速度提高一倍)。
答案 3 :(得分:2)
"Lorem Lorem Lorem".scan(/\S+/).size
=> 3
答案 4 :(得分:2)
这里的答案有几个问题:
Joe's
将被视为两个单词Joe
和's
,这显然是不正确的。和twenty-two
一样,这是一个复合词。这样的事情可以更好地解决这些问题:
foo.scan(/[\p{Alpha}\-']+/)
您可能需要查看我的 Words Counted gem。它允许计算单词,它们的出现次数,长度和其他一些东西。它也有很好的记录。
counter = WordsCounted::Counter.new(post.body)
counter.word_count #=> 3
counter.most_occuring_words #=> [["lorem", 3]]
# This also takes into capitalisation into account.
# So `Hello` and `hello` are counted as the same word.
答案 5 :(得分:1)
"caçapão adipisicing elit".scan(/[\w-]+/).size
=> 5
但正如我们所看到的,这句话只有3个字。问题与重音字符有关,因为正则表达式\ w不将它们视为单词字符[A-Za-z0-9 _]。
改进的解决方案是
I18n.transliterate("caçapão adipisicing elit").scan(/[\w-]+/).size
=> 3