擦洗文本变得非常棘手。你要注意的一件事是字界。因空间分割会让许多嘟嘟的单词由于念头而得以通过。比较下面示例代码的前两个结果。
接下来,将分割文本重新组装到预期形式中,使用punction,spacing等等,将变得非常具有挑战性。您可能要考虑使用正则表达式来预先设定与用户注释一样小的内容。看到第三个结果。
如果你将此作为一种学习练习,那很好,但如果应用程序对敏感的地方很容易受到失败煽风点火的困扰,那么你可能需要寻找一个经过良好测试的库。
#!/usr/bin/env ruby
# Bleeper
scifi_curses = ['friggin', 'gorram', 'fracking', 'dork']
text = "Why splitting spaces won't catch all the friggin bleeps ya gorram, fracking dork."
words = text.split(" ")
words.each do |this_word|
puts "bleep #{this_word}" if scifi_curses.include?(this_word)
end
puts
better_words = text.split(/\b/)
better_words.each do |this_word|
puts "bleep #{this_word}" if scifi_curses.include?(this_word)
end
puts
bleeped_text = text # keep copy of original if needed
scifi_curses.each do |this_curse|
bleeped_text.gsub!(this_curse, '[bleep]')
end
puts bleeped_text
你应该得到这些结果:
bleep friggin
bleep fracking
bleep friggin
bleep gorram
bleep fracking
bleep dork
Why splitting spaces won't catch all the [bleep] bleeps ya [bleep], [bleep] [bleep].