【问题标题】:Getting viewable text words via Nokogiri通过 Nokogiri 获取可见的文本单词
【发布时间】:2011-05-25 18:51:59
【问题描述】:

我想用 Nokogiri 打开一个网页,提取用户在浏览器中访问该页面时看到的所有词并分析词频。

使用 nokogiri 从 html 文档中获取所有可读单词的最简单方法是什么?理想的代码 sn-p 将获取一个 html 页面(例如,作为一个文件)并给出一个由所有类型的可读元素组成的单个单词的数组。

(无需担心 javascript 或 css 隐藏元素从而隐藏文字;所有设计用于显示的文字都可以。)

【问题讨论】:

  • 仅供参考,最有趣的词通常不是出现最多的词。你应该看看 TF-IDF:goo.gl/M0iuE

标签: ruby nokogiri


【解决方案1】:

你想要Nokogiri::XML::Node#inner_text 方法:

require 'nokogiri'
require 'open-uri'
html = Nokogiri::HTML(open 'http://stackoverflow.com/questions/6129357')

# Alternatively
html = Nokogiri::HTML(IO.read 'myfile.html')

text  = html.at('body').inner_text

# Pretend that all words we care about contain only a-z, 0-9, or underscores
words = text.scan(/\w+/)
p words.length, words.uniq.length, words.uniq.sort[0..8]
#=> 907
#=> 428
#=> ["0", "1", "100", "15px", "2", "20", "2011", "220px", "24158nokogiri"]

# How about words that are only letters?
words = text.scan(/[a-z]+/i)
p words.length, words.uniq.length, words.uniq.sort[0..5]
#=> 872
#=> 406
#=> ["Answer", "Ask", "Badges", "Browse", "DocumentFragment", "Email"]
# Find the most frequent words
require 'pp'
def frequencies(words)
  Hash[
    words.group_by(&:downcase).map{ |word,instances|
      [word,instances.length]
    }.sort_by(&:last).reverse
  ]
end
pp frequencies(words)
#=> {"nokogiri"=>34,
#=>  "a"=>27,
#=>  "html"=>18,
#=>  "function"=>17,
#=>  "s"=>13,
#=>  "var"=>13,
#=>  "b"=>12,
#=>  "c"=>11,
#=>  ...

# Hrm...let's drop the javascript code out of our words
html.css('script').remove
words = html.at('body').inner_text.scan(/\w+/)
pp frequencies(words)
#=> {"nokogiri"=>36,
#=>  "words"=>18,
#=>  "html"=>17,
#=>  "text"=>13,
#=>  "with"=>12,
#=>  "a"=>12,
#=>  "the"=>11,
#=>  "and"=>11,
#=>  ...

【讨论】:

  • 您似乎知道自己在做什么——知道如何获取文本中的行数吗?我正在解析一个带有


    标签的诗体。

  • @Kevin 提出问题(而不是作为对答案的评论),您可能会得到所需的解决方案。有多种方法,但这取决于您的输入和确切的愿望。
【解决方案2】:

如果你真的想用 Nokogiri 来做这件事(否则你可以使用正则表达式来去除标签),那么你应该:

  1. doc = Nokogiri::HTML(open('url').read) #open-uri
  2. 使用类似 doc.search('script').each {|el| 之类的东西去除所有 javascript 和样式标签el.unlink}
  3. doc.text

【讨论】:

    【解决方案3】:

    更新:从 ruby​​ 2.7 开始 - 有新的 Enumerable 方法 - tally - 计算出现次数

    所选答案中的错误: html.at('body').inner_text - 将连接所有节点的所有文本 - 没有空格。例如文档包含:

    <html><body><p>this</p><p>text</p></body><html>

    将产生“thistext”

    更好:使用this answer

    html = Nokogiri::HTML(open 'http://stackoverflow.com/questions/6129357')
    text = html.xpath('.//text() | text()').map(&:inner_text).join(' ')
    occurrences = text.scan(/\w+/).map(&:downcase).tally
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多