【问题标题】:Ruby: Titleize: How do I ignore smaller words like 'and', 'the', 'or, etcRuby:Titleize:如何忽略较小的单词,例如“and”、“the”、“or”等
【发布时间】:2013-02-11 07:18:44
【问题描述】:
def titleize(string)
  string.split(" ").map {|word| word.capitalize}.join(" ")
end

这会为每个单词加上标题,但我如何捕捉某些我不想大写的单词?

即)杰克和吉尔

请不要使用正则表达式。

更新:

我无法使这段代码正常工作:我让它打印一个全部大写的单词数组,但不是没有下面的列表。

words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]

def titleize(string)
cap_word = string.split(" ").map {|word| word.capitalize}

cap_word.include?(words_no_cap)

end

【问题讨论】:

  • 您创建了一个所谓的“停用词”列表,其中包含您不想处理的单词。它可以是数组、集合、散列或正则表达式。正则表达式和哈希一样是处理问题的常用方法,因为它们都非常快。另外,不要拒绝回答说“不要使用...”。我们提供我们认为是解决问题的最佳解决方案,您可以随意不实施。
  • “不要使用正则表达式”在给出的示例代码中听起来有争议,因为string.split 实际上确实使用了正则表达式。您可能想要已经准备好使用的东西——然后看看titleize。它可以作为 gem 安装。

标签: ruby string


【解决方案1】:

我认为短语的第一个单词必须大写:

class String

  def uncapitalize_puncs
    puncs = ["and", "the", "to", "of", "by", "from", "or"]
    array = self.split(" ")
    i = -1
    array.map! do |x|
      i += 1
      if puncs.include?(x.downcase) && i > 0
        x.downcase
      else
        x
      end
    end
    array.join(" ")
  end

end

【讨论】:

    【解决方案2】:
    titleize("the matrix or titanic")
    
    def titleize(string)
      no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
      string.split(" ").map { |word| no_cap.include?(word) ? word : 
      word.capitalize }.join(" ")
    end
    

    结果:

    "the Matrix or Titanic"
    

    【讨论】:

      【解决方案3】:

      metodo 首字母大写

      def capitalizar_titulo(string)
          words_not_to_capitalize = ["a","e","i","o","u","ao","aos", "as", "nos","nós","no","na","mas", "mes", "da", "de", "di", "do", "das", "dos"]
          s = string.split.each{|str| str.capitalize! unless words_not_to_capitalize.include? (str.downcase) }
          s[0].capitalize + " " + s[1..-1].join(" ")
        end
      

      【讨论】:

      • 欢迎来到 Stack Overflow!您可以阅读有关如何How to Answer 的问题。 SO 是一个英文网站。
      【解决方案4】:

      有些标题有可能需要考虑的极端情况(双关语)。

      例如,标题开头或标点符号之后的小词通常应大写(例如“纳尼亚传奇:狮子、女巫和魔衣橱”两者都有)。

      人们可能还希望/需要将小字强制小写,以便将“Jack And Jill”等输入呈现为“Jack and Jill”。

      有时您可能还需要检测单词(通常是品牌名称)何时必须保留不寻常的大写,例如“iPod”或首字母缩略词,例如“NATO”,或域名,“example.com”。

      要正确处理此类情况,titleize gem 是您的朋友,或者至少应该为完整的解决方案提供基础。

      【讨论】:

        【解决方案5】:

        如果您不想大写 and 或 the,只需执行以下操作:

        def titleize(string)
          nocaps = "and"
          string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")
        end
        

        【讨论】:

          【解决方案6】:

          您可能想要为 Rails 提供的 existing titleize 函数创建一个扩展。

          为此,只需在初始化程序中包含以下文件,然后就可以了!即时提供异常或选择性地修改我的示例以将默认值添加到初始化程序中。

          我知道你不想使用 Regex,但是,实际的 rails 函数使用 Regex,所以你最好保持同步。

          将此文件放入Rails.root/lib/string_extension.rb 并在初始化程序中加载它;或者只是将其放入初始化程序本身。

          更新:感谢@svoop 建议添加结束词边界,修改了正则表达式。

          # encoding: utf-8
          class String
            def titleize(options = {})
              exclusions = options[:exclude]
          
              return ActiveSupport::Inflector.titleize(self) unless exclusions.present?
              self.underscore.humanize.gsub(/\b(?<!['’`])(?!(#{exclusions.join('|')})\b)[a-z]/) { $&.capitalize }
            end
          end
          

          【讨论】:

            【解决方案7】:

            如果您将其放入 config/initializers 中并放入一个新文件(您可以将其命名为 string.rb 之类的任何名称),您可以将自定义函数调用到任何字符串。确保你重新启动,然后你将能够像 ex) "anystring".uncapitalize_puncs 一样在下面运行

            这比尝试更改 titleize 的默认代码更容易。所以现在,你可以打电话给@something.title.titleize.uncapitalize_puncs

            class String
            
                def uncapitalize_puncs
                    puncs = ["and", "the", "to", "of", "by", "from", "or"]
                    array = self.split(" ")
                    array.map! do |x| 
                        if puncs.include? x.downcase
                            x.downcase
                        else
                            x
                        end
                    end
                    return array.join(" ")
                end
            
            end
            

            【讨论】:

              【解决方案8】:

              这是我的小代码。您可以将其折射为几行。

              def titleize(str)
                  str.capitalize!  # capitalize the first word in case it is part of the no words array
                  words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
                  phrase = str.split(" ").map {|word| 
                      if words_no_cap.include?(word) 
                          word
                      else
                          word.capitalize
                      end
                  }.join(" ") # I replaced the "end" in "end.join(" ") with "}" because it wasn't working in Ruby 2.1.1
                phrase  # returns the phrase with all the excluded words
              end
              

              【讨论】:

                【解决方案9】:

                @codenamev 的回答不太行:

                EXCLUSIONS = %w(a the and or to)
                "and the answer is all good".titleize(exclude: EXCLUSIONS)
                # => "And the Answer Is all Good"
                                        ^^^
                

                排除项应匹配尾随单词边界。这是一个改进的版本:

                # encoding: utf-8
                class String
                  def titleize(options = {})
                    exclusions = options[:exclude]
                
                    return ActiveSupport::Inflector.titleize(self) unless exclusions.present?
                    self.underscore.humanize.gsub(/\b(['’`]?(?!(#{exclusions.join('|')})\b)[a-z])/) { $&.capitalize }
                  end
                end
                
                "and the answer is all good".titleize(exclude: EXCLUSIONS)
                # => "And the Answer Is All Good"
                                        ^^^
                

                【讨论】:

                  【解决方案10】:

                  这很简单,只需在调用captalize时添加一个条件:

                  $nocaps = ['Jack', 'Jill']
                  
                  def titleize(string)
                    string.split(" ").map {|word| word.capitalize unless $nocaps.include?(word)}.join(" ")
                  end
                  

                  全局变量是为本示例设计的,它可能是您实际应用程序中的实例变量。

                  【讨论】:

                  • if not 应该是 unless。但这会减慢nocaps 列表的速度,因为include? 必须按顺序遍历数组。
                  • @theTinMan 好点,我倾向于不使用unless,即使在这种情况下。无论如何,有人显然不喜欢这个解决方案。但他们没有发表评论。
                  猜你喜欢
                  • 2012-06-02
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-09-09
                  • 2022-01-12
                  • 2011-03-16
                  • 2020-02-03
                  • 1970-01-01
                  相关资源
                  最近更新 更多