我正在编写一个脚本来为subreddit提取注释,分解单个单词,计算它们并对它们进行排序。大约70%的时间我收到此错误:
in `<main>': undefined method `map' for nil:NilClass (NoMethodError) Did you mean? tap
大约30%的时间,脚本按预期工作。为什么会这样?你会如何解决?我是编程新手,所以如果问题是基本的话,我会感到惊讶。这是我的代码:
require 'net/http'
require 'rubygems'
require 'json'
# Pull json file, parse out comments
url = 'https://www.reddit.com/r/askreddit/comments.json?sort=top&t=all&limit=100'
uri = URI(url)
response = Net::HTTP.get(uri)
json = JSON.parse(response)
comments = json.dig("data", "children").map { |child| child.dig("data", "body") }
#Split words into array
words = comments.to_s.split(/[^'\w]+/)
words.delete_if { |a,_| a.length < 5}
#count and sort words
count = Hash.new(0)
words.each { |word| count.store(word, count[word]+1)}
count.delete_if { |_,b| b < 4}
sorted = count.sort_by { |word,count| count}.reverse
puts sorted
答案 0 :(得分:1)
您的json.dig("data", "children")
似乎偶尔会返回nil
。优雅处理此问题的一种方法是使用safe navigation operator (&.):
comments = json.dig("data", "children")&.map { |child| child.dig("data", "body") }
if comments
# your other logic with comments here
else
{}
end
答案 1 :(得分:0)
Reddit方面基本上存在错误。我写了一个解决方法,但它有时会有一点延迟;它一遍又一遍地尝试直到成功。 编辑(大部分)与原始代码匹配。
require 'net/http'
require 'rubygems'
require 'json'
# Pull json file, parse out comments
url = 'https://www.reddit.com/r/askreddit/comments.json?sort=top&t=all&limit=100'
uri = URI(url)
error = true
while error
response = Net::HTTP.get(uri)
json = JSON.parse(response)
error = json["error"]
end
comments = json.dig("data", "children").map { |child| child.dig("data", "body") }
#Split words into array
words = comments.to_s.split(/[^'\w]+/)
words.delete_if { |a,_| a.length < 5}
#count and sort words
count = Hash.new(0)
words.each { |word| count.store(word, count[word]+1)}
count.delete_if { |_,b| b < 4}
sorted = count.sort_by { |word,count| count}.reverse
puts sorted