2017-03-13 26 views
1

我正在使用Twitter gem生成包含图像的特定哈希标签的最新推文列表。Twitter API:如何在标签结尾处匹配标点符号?

它工作正常,但我注意到,当人们在他们的推文中向标签添加标点符号时,API不会将它们包括在我的搜索结果中。为了说明这一点,当我搜索#sourcecon它不包括使用#sourcecon!

运行通过API独立搜索#sourcecon.#sourcecon!没有帮助鸣叫 - 它忽略了punctation并产生相同的列表。

我的代码是在这里:

twitter_client.search("'#sourcecon' filter:images", result_type: "recent", :since_id => last_tweet).collect 

VS

twitter_client.search("'#sourcecon!' filter:images", result_type: "recent", :since_id => last_tweet).collect 

我知道Twitter把标点符号不作为主题标签的一部分。从Twitter的API:

注意标点符号不被认为是一个#hashtag或@mention的一部分,所以含标点符号轨道内不会匹配任何一种或#哈希标签@mentions。

但不应该意味着它会完全忽略它,并返回所有结果(包括包含在该微博所附的标点符号的人?)

有谁知道如何让搜索结果在这里,会在最后包括提及标签的标签吗?

回答

2

使用twitter搜索标点符号和特殊字符将被视为您正在搜索的术语的一部分,因此搜索'#twitter!'将会返回“#twitter!”,“twitter?”,“#twitter”等。你可以做的是检查搜索是否包含任何类型的标点符号搜索,如果它可以排序数组首先添加这些推文。

require 'twitter' 

module TwitterSearch 
    extend self 

    @twiiter_client = Twitter::REST::Client.new do |config| 
    config.consumer_key  = "" 
    config.consumer_secret  = "" 
    config.access_token  = "" 
    config.access_token_secret = "" 
    end 

    # search returns 
    # Check out what @researchgoddess is up to at #sourcecon! 
    # What a welcome from @SourceCon! Thanks @CareerBuilder for hosting.# 
    # RT @JRoberts257: Happy hour at #SourceCon! Thanks @CareerBuilder for 
    # Happy hour at #SourceCon! Thanks @CareerBuilder for sponsoring. ht 
    # @RT @cybsearchjoe: #SourceCon is rocking 
    # etc 

    def search(text) 
    tweets = @twitter_client.search("#{text} filter:images", result_type: "recent").take(30).collect do |tweet| 
     "#{tweet.text}" 
    end 
    # looks to see if there is puncuation at the end of the text "!.?{}[]" It will ignore the # at the beginning 
    tweets = sort_tweets(text, tweets) if text[1..text.length] =~ /[[:punct:]]/ 
    puts tweets 
    end 


    # sorts tweets based off index given in match_phrase 
    def sort_tweets(text, tweets) 
    tweets.sort do |phrase, other_phrase| 
     match_phrase(phrase, text, tweets) <=> match_phrase(other_phrase, text, tweets) 
    end 
    end 

    # if phrase matches punc_text(text) the phrase will be inserted at the beginning of the array else it will return its previous index. 
    def match_phrase(phrase, text, tweets) 
    phrase.match(/#{punc_text(text)}/i).nil? ? tweets.index(phrase) + 1 : 0 
    end 

    # adds backslash to punctuation '#sourcecon//?|!|.' 
    def punc_text(text) 
    text[1..text.length].gsub(/([[:punct:]])/){|punc| "\\#{punc}"} 
    end 
end 

TwitterSearch.search('#sourcecon!') 
+0

如果我正确地理解这个,这是什么样的我想做的事情。我想获得一个使用#标签,包括标点符号的,而不是分开的一切搜索结果相反的他们出来 – dmanaster

+0

对不起,混淆更新了答案,使更有意义。 –