【问题标题】:Ruby: Convert HTML/Redcloth to plain textRuby:将 HTML/Redcloth 转换为纯文本
【发布时间】:2009-06-05 09:33:05
【问题描述】:

有谁知道我如何使用 Ruby 将 html 转换为纯文本。好吧,我真的需要将 RedCloth 转换为纯文本,无论哪种方式都可以。

我不是在谈论仅仅删除标签(这就是我到目前为止所做的一切)。例如,我想要一个有序列表来保留数字,无序列表使用星号表示项目符号等。

 def red_cloth_to_plain_text(s)
       s = RedCloth.new(s).to_html
       s = strip_tags(s)
       s = html_unescape(s) # reverse of html_escape
       s = undo_red_cloths_html_codes(s)
       return s 
 end

也许我必须尝试将 RedCloth 转换为纯文本格式化程序

【问题讨论】:

    标签: ruby formatting


    【解决方案1】:

    您需要创建一个新的格式化程序类。

    module RedCloth::Formatters
      module PlainText
        include RedCloth::Formatters::Base
        # ...
      end
    end
    

    我今天不会为你编写代码,但这很容易做到。如果您怀疑我,请阅读 RedCloth 源代码:HTML 格式化程序只有 346 行。

    所以,一旦你有了纯文本格式化程序,你就可以修补类并使用它:

    module RedCloth
      class TextileDoc
        def to_txt( *rules )
          apply_rules(rules)
          to(RedCloth::Formatters::PlainText)
        end
      end
    end
    
    print RedCloth.new(str).to_txt
    

    【讨论】:

      【解决方案2】:

      Joseph Halter 编写了一个 RedCloth 普通格式化程序:

      http://github.com/JosephHalter/redcloth-formatters-plain

      示例用法:

      RedCloth.new("p. this is *simple* _test_").to_plain
      

      将返回:

      "this is simple test"
      

      【讨论】:

        【解决方案3】:

        这可能是你必须做的。 You're not the first to want this,但我猜它还不是库的一部分,因为每个人都希望他们的明文有点不同。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-12
          • 2014-09-08
          • 2018-03-17
          • 1970-01-01
          • 2014-04-21
          • 1970-01-01
          相关资源
          最近更新 更多