Skip to content

Instantly share code, notes, and snippets.

@linxlunx
Created May 16, 2015 02:11
Show Gist options
  • Save linxlunx/e465abe2aab91754aff7 to your computer and use it in GitHub Desktop.
Save linxlunx/e465abe2aab91754aff7 to your computer and use it in GitHub Desktop.
Search and Count Mentioned Users (Twitter)
package main
import (
"github.com/ChimeraCoder/anaconda"
"fmt"
"log"
"net/url"
"strings"
"sort"
"regexp"
)
const (
ConsumerKey = "Insert Consumer Key"
ConsumerSecret = "Insert Consumer Secret"
AccessKey = "Insert Access Key"
AccessSecret = "Insert Access Secret"
)
type Person struct {
Name string
Total int
}
type People []*Person
func (p People) Len() int { return len(p) }
func (p People) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type ByTotal struct{ People }
func (s ByTotal) Less(i, j int) bool { return s.People[i].Total > s.People[j].Total }
var m map[string]int
var Word string
var AllWord []string
func GetTweet(search string) (result string) {
anaconda.SetConsumerKey(ConsumerKey)
anaconda.SetConsumerSecret(ConsumerSecret)
api := anaconda.NewTwitterApi(AccessKey, AccessSecret)
v := url.Values{}
v.Set("count", "100")
searchRes, err := api.GetSearch(search, v)
if err != nil {
log.Fatal(err)
}
for _, tweet := range searchRes.Statuses {
AllWord = append(AllWord, tweet.Text)
}
nextTweet, err := searchRes.GetNext(api)
if err != nil {
log.Fatal(err)
}
for len(nextTweet.Statuses) > 0 {
for _, tweetNext := range nextTweet.Statuses {
AllWord = append(AllWord, tweetNext.Text)
}
nextTweet, err = nextTweet.GetNext(api)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(nextTweet.Statuses))
}
result = strings.Join(AllWord, ", ")
return result
}
func GetMention(crawled string, Word string) (mentioned []string) {
re := regexp.MustCompile("[^a-zA-Z0-9_@]")
data := strings.Split(crawled, " ")
for _, o := range data {
if strings.HasPrefix(o, "@") {
cleanPeople := re.ReplaceAllLiteralString(o, "")
if cleanPeople != Word {
mentioned = append(mentioned, cleanPeople)
}
}
}
return mentioned
}
func main() {
Word = "@linxlunx"
AllTweet := GetTweet(Word)
MentionedPeople := GetMention(AllTweet, Word)
m = make(map[string]int)
for _, per := range MentionedPeople {
_, ok := m[per]
if ok {
m[per]++
} else {
m[per] = 1
}
}
s := []*Person{}
for k, v := range m {
s = append(s, &Person{k, v})
}
sort.Sort(ByTotal{s})
for _, x := range s {
fmt.Printf("%s %d\n", x.Name, x.Total)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment