【发布时间】:2017-09-22 17:42:53
【问题描述】:
给定一个句子,我想统计所有重复的单词:
这是来自 Exercism.io 的一个练习 Word count
例如对于输入"olly olly in come free"
plain
olly: 2
in: 1
come: 1
free: 1
我有这个测试的例子:
def test_with_quotations
phrase = Phrase.new("Joe can't tell between 'large' and large.")
counts = {"joe"=>1, "can't"=>1, "tell"=>1, "between"=>1, "large"=>2, "and"=>1}
assert_equal counts, phrase.word_count
end
这是我的方法
def word_count
phrase = @phrase.downcase.split(/\W+/)
counts = phrase.group_by{|word| word}.map {|k,v| [k, v.count]}
Hash[*counts.flatten]
end
对于上面的测试,当我在终端中运行它时出现此故障:
2) Failure:
PhraseTest#test_with_apostrophes [word_count_test.rb:69]:
--- expected
+++ actual
@@ -1 +1 @@
-{"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1}
+{"first"=>1, "don"=>2, "t"=>2, "laugh"=>1, "then"=>1, "cry"=>1}
我的问题是删除除'apostrophe 之外的所有字符...
该方法中的正则表达式几乎可以工作...
phrase = @phrase.downcase.split(/\W+/)
但它删除了撇号...
我不想在单词周围保留单引号,'Hello' => Hello
但是Don't be cruel => Don't be cruel
【问题讨论】:
-
试试
/[^'a-z]/ -
或试试这个:
/[a-z']+/i -
它保留单引号 :( @dagw
-
@sagarpandya82 都不是
-
似乎有些混乱,您能否澄清一下您的问题。也许给一个更详尽的例子。>>> 好的,你已经完成了,你现在可以为你的第二个例子说明所需的输出吗?