【问题标题】:How to parse an article from web-page using Regexp?如何使用正则表达式解析网页中的文章?
【发布时间】:2013-06-20 19:53:12
【问题描述】:

我在页面上有一篇文章,我需要解析所有文本。

我知道一篇文章超过 15 个字,用符号“”或“,”或“-”或“:”或“.”连接。

如何使用 Ruby 编写 Regexp 来分析页面上的文章并解析它?

例如:http://www.nytimes.com/2013/06/20/sports/baseball/for-the-mets-an-afterglow-then-realitys-harsh-light.html?ref=sports&_r=0

我需要解析正文:ATLANTA — From the sublime emotional high provided by Matt Harvey and Zack Wheeler, the Mets’ young, hard-throwing right-handers, the team on Wednesday descended back to the realities of its everyday existence...

我知道如何解析和获取页面内容,但我不知道如何在 Regexp 上编写它! 要分析带有所需文本的父 HTML 标记,我必须编写一些正则表达式来检查规则: 文章超过 15 个字,仅使用符号“”或“,”或“-”或“:”或“.”连接。

【问题讨论】:

  • 需要更多信息、示例字符串或输入以及预期输出。
  • Mechanize 带有 nokogiri。因此,您可以使用 mechanize 实例中的所有 nokogiri 方法。有很多教程和文档可以证明这一点。
  • 在需要报废时使用 Nokogiri

标签: ruby regex mechanize


【解决方案1】:

查看Nokogiri 以满足您的需求。这是一个很棒的网页抓取工具。

require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('http://www.nytimes.com/2013/06/20/sports/baseball/for-the-mets-an-afterglow-then-realitys-harsh-light.html?ref=sports&_r=1&'))
str = doc.at_css('div.articleBody > nyt_text > p').text 

puts str
# >> ATLANTA — From the sublime emotional high provided by Matt Harvey and Zack Wheeler, the Mets’ young, hard-throwing right-handers, the team on Wednesday descended back to the realities of its everyday existence.  

str.scan(/\w+/)
# => ["ATLANTA",
#     "From",
#     "the",
#     "sublime",
#     "emotional",
#     "high",
#     "provided",
#     "by",
#     "Matt",
#     "Harvey",
#     "and",
#     "Zack",
#     "Wheeler",
#     "the",
#     "Mets",
#     "young",
#     "hard",
#     "throwing",
#     "right",
#     "handers",
#     "the",
#     "team",
#     "on",
#     "Wednesday",
#     "descended",
#     "back",
#     "to",
#     "the",
#     "realities",
#     "of",
#     "its",
#     "everyday",
#     "existence"]

我知道这篇文章超过 15 个字:

str.scan(/\w+/).size > 15 # => true

用符号“”或“,”或“-”或“:”或“.”连接:

[' ',',','-',':','.'].map{|i| str.include? i}
# => [true, true, true, false, false]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2016-08-19
    • 2016-04-27
    • 1970-01-01
    • 2020-09-17
    • 2013-07-08
    相关资源
    最近更新 更多