首页 > 解决方案 > 如何使用计数器方法打印返回的只有英文的推文数量?

问题描述

我正在使用 twitter api,在其中搜索包含关键字“Lebron”的推文。我正在尝试编写一个循环来计算仅英文的推文数量并包含关键字“Lebron”。我正在使用 Atom 作为我的文本编辑器在 ruby​​ 中编写这个。

ps - 我已经可以访问 Twitter,我只是没有显示完整的密钥

require 'twitter'

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "8t4G...aa6"
  config.consumer_secret     = "tmq...bFA"
  config.access_token        = "106...OwI"
  config.access_token_secret = "LDh...VnB"
end

def tweet_count
  tweet_count.count do |e|
  e == lang: "en"
  end

client.search("Lebron -rt", result_type: "recent").take(2).each do |tweet|
  puts "#{tweet.user.screen_name}: #{tweet.text}" #tweet.text
end

标签: rubyrestapitwitterrubygems

解决方案


Twitter Ruby gem的文档指出,您可以使用该:lang选项将搜索结果限制为任何ISO-639-1 语言 id

tweet_count = client.search("Lebron", lang: "en", result_type: "recent").count
puts "Found #{tweet_count} tweets in English"

推荐阅读