代码之家  ›  专栏  ›  技术社区  ›  tsdbrown

Ruby:将HTML/RedCloth转换为纯文本

  •  2
  • tsdbrown  · 技术社区  · 16 年前

    有人知道我如何用Ruby将HTML转换成纯文本吗?好吧,我真的需要把红布转换成纯文本,无论哪种方式都可以。

    我说的不是简单地去掉标签(这是我迄今为止所做的)。例如,我想要一个有序的列表来保留数字,无序的列表使用星号来表示项目符号等。

     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
    

    也许我必须尝试一个红布到纯文本格式设置工具

    3 回复  |  直到 16 年前
        1
  •  2
  •   Robert K    16 年前

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

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

    我今天不给你写代码,但这很容易。如果您怀疑我,请阅读红布源代码: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
  •  2
  •   Josiah I.    15 年前

    约瑟夫·哈尔特(Joseph Halter)写了一篇红布素色的格式化文章:

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

    示例用法:

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

    将返回:

    "this is simple test"
    
        3
  •  0
  •   rampion    16 年前

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