我正在嘗試提取一篇文章的摘錄(降價決議為 HTML),其中僅包含段落中的純文本。所有的 HTML 都需要被剝離,換行符、制表符和連續的空格需要被一個空格替換。
我的第一步是創建一個簡單的測驗:
describe "#from_html" do
it "creates an excerpt from given HTML" do
html = "<p>The spice extends <b>life</b>.<br>The spice expands consciousness.</p>\n
<ul><li>Skip me</li></ul>\n
<p>The <i>spice</i> is vital to space travel.</p>"
text = "The spice extends life. The spice expands consciousness. The spice is vital to space travel."
expect(R::ExcerptHelper.from_html(html)).to eq(text)
end
end
并開始擺弄并想出了這個:
def from_html(html)
Nokogiri::HTML.parse(html).css("p").map{|node|
node.children.map{|child|
child.name == "br" ? child.replace(" ") : child
} << " "
}.join.strip.gsub(/\s /, " ")
end
我在 Rails 上有點生疏,這可能會更高效、更優雅。我希望在這里得到一些指示。
提前致謝!
方法二
轉向sanitize方法(感謝@max)并基于Rails::Html::PermitScrubber
方法 3
意識到我的源檔案被格式化為 Markdown,我冒險探索了一個自定義的Redcarpet渲染器。
有關完整示例,請參閱我的答案。
uj5u.com熱心網友回復:
我最終撰寫了一個自定義Redcarpet渲染器(靈感來自Redcarpet::Render::StripDown)。這似乎是最簡潔的方法,格式之間的決議和轉換最少。
module R::Markdown
class ExcerptRenderer < Redcarpet::Render::Base
# Methods where the first argument is the text content
[
# block-level calls
:paragraph,
# span-level calls
:codespan, :double_emphasis,
:emphasis, :underline, :raw_html,
:triple_emphasis, :strikethrough,
:superscript, :highlight, :quote,
# footnotes
:footnotes, :footnote_def, :footnote_ref,
# low level rendering
:entity, :normal_text
].each do |method|
define_method method do |*args|
args.first
end
end
# Methods where content is replaced with an empty space
[
:autolink, :block_html
].each do |method|
define_method method do |*|
" "
end
end
# Methods we are going to [snip]
[
:list, :image, :table, :block_code
].each do |method|
define_method method do |*|
" [#{method}] "
end
end
# Other methods
def link(link, title, content)
content
end
def header(text, header_level)
" #{text} "
end
def block_quote(quote)
" “#{quote}” "
end
# Replace all whitespace with single space
def postprocess(document)
document.gsub(/\s /, " ").strip
end
end
end
并決議它:
extensions = {
autolink: true,
disable_indented_code_blocks: true,
fenced_code_blocks: true,
lax_spacing: true,
no_intra_emphasis: true,
strikethrough: true,
superscript: true,
tables: true
}
markdown = Redcarpet::Markdown.new(R::Markdown::ExcerptRenderer, extensions)
markdown.render(md).html_safe
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440713.html
標籤:html 轨道上的红宝石 红宝石 html-parsing nokogiri
上一篇:引數的rspec測驗失敗
