【问题标题】:How to filter Twitter API mentions如何过滤 Twitter API 提及
【发布时间】:2017-08-06 18:35:51
【问题描述】:

我正在使用 Twitter gem 创建一个项目,需要过滤从mentions_timeline 收到的推文。

我想过通过阅读推文文本的几个if 语句进行过滤:

require 'sinatra'
require 'twitter'
require 'sinatra/reloader'

include ERB::Util

before do
  config = {
      :consumer_key => 'xxx',
      :consumer_secret => 'xxx',
      :access_token => 'xxx',
      :access_token_secret => 'xxx'
  }
    @client = Twitter::REST::Client.new(config)
end

get '/order' do
  @tweets = @client.mentions_timeline
  @collect_tweets = Array.new
  @delivery_tweets = Array.new

  @tweets.each do |tweet|
    if (tweet.text.include? "order" && tweet.text.include? "collect")
      @collect_tweets.push(tweet)
    elsif (tweet.text.include? "order" && tweet.text.include? "delivery")
      @delivery_tweets.push(tweet)
    end

  erb :order
end

但它不会起作用。

我收到此错误:

/Users/me/Projects/team-13/order.rb:23: syntax error, unexpected tSTRING_BEG, expecting ')' rder" && tweet.text.include? "collect") ^ /Users/me/Projects/team-13/order.rb:25: syntax error, unexpected tSTRING_BEG, expecting ')' rder" && tweet.text.include? "delivery") ^ /Users/me/Projects/team-13/order.rb:30: syntax error, unexpected end-of-input, expecting keyword_end

【问题讨论】:

  • 请阅读“minimal reproducible example”。我们只需要足够的代码来运行 和测试以复制问题。我们还需要最少的支持数据来帮助证明这一点。否则,它会浪费我们的时间。 SO 不是您提到的“帮助我”网站,但为了帮助他人,我们需要某些东西。
  • 为了复制问题,您需要拥有 twitter 密钥,我显然不会在这里发布。我只是想知道是否有人对 ruby​​ 有更多的专业知识,而不是我所拥有的小知识,是否会看到一个可能是问题的大语法错误。无论如何,在我没有具体说明问题本身的意义上,你是对的。谢谢你告诉我,我会编辑帖子;)

标签: ruby twitter rubygems


【解决方案1】:

您的代码中有一些错误。

代码中第 23 行和第 25 行的第一个是 include? 方法的参数需要括号。当您像您一样列出多种方法时,您需要这样做。您可以将其更改为:

if (tweet.text.include?("order") && tweet.text.include?("collect"))

第 30 行的另一个错误是您的每个循环都缺少 end

each 循环应该如下所示:

@tweets.each do |tweet|
    if (tweet.text.include?("order") && tweet.text.include?("collect"))
        @collect_tweets.push(tweet)
    elsif (tweet.text.include?("order") && tweet.text.include?("delivery"))
        @delivery_tweets.push(tweet)
    end
end

【讨论】:

  • 没错,我是在阅读其他人的评论后才知道的,就在我来这里结束这篇文章时,我看到了你的答案。无论如何都非常感谢。感谢您花时间回答的一样好???
  • 小心称它们为“括号”([...])。它们是括号 ((...))。您可以称它们为“方括号”和“圆括号”,但它们通常被称为括号和圆括号,在此用途中不可互换。此外,这些是方法,而不是函数。
【解决方案2】:

你没有关闭你的每个块:

'order.rb:30: syntax error, unexpected end-of-input, expecting keyword_end'

阅读错误消息,它会告诉您在哪里修复它。

   @tweets.each do |tweet|
     if (tweet.text.include? "order" && tweet.text.include? "collect")
      @collect_tweets.push(tweet)
     elsif (tweet.text.include? "order" && tweet.text.include? "delivery")
      @delivery_tweets.push(tweet)
     end
   end

【讨论】:

  • 真的!非常感谢!我想我只需要更好地阅读错误......哈哈
猜你喜欢
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多