Skip to content

Instantly share code, notes, and snippets.

@Zhang-Siyang Zhang-Siyang/niub.go
Last active Aug 4, 2019

Embed
What would you like to do?
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"time"
)
// 单名用户
type member struct {
Username string `json:"username"`
Website string `json:"website"`
Github string `json:"github"`
Psn string `json:"psn"`
Avatar_normal string `json:"avatar_normal"`
Bio string `json:"bio"`
Url string `json:"url"`
Tagline string `json:"tagline"`
Twitter string `json:"twitter"`
Created int `json:"created"`
Avatar_large string `json:"avatar_large"`
Avatar_mini string `json:"avatar_mini"`
Location string `json:"location"`
Btc string `json:"btc"`
Id int `json:"id"`
}
// 单个回复
type reply struct {
Member member `json:"member"`
Created int `json:"created"`
Topic_id int `json:"topic_id"`
Content string `json:"content"`
Content_rendered string `json:"content_rendered"`
Last_modified int `json:"last_modified"`
Member_id int `json:"member_id"`
Id int `json:"id"`
}
func main() {
// 读入文件
fileContent, err := ioutil.ReadFile("v2ex_t587422_replies.json")
if err != nil {
log.Fatal(err)
os.Exit(-1)
//TODO 查一下是不是应该这样退出,不过统一退出似乎是最优选?
}
// 从json字符串解析回对象列表
var replies []reply
err = json.Unmarshal(fileContent, &replies)
if err != nil {
log.Fatal(err)
os.Exit(-1)
}
// 统计用户回复数量
var memberCount = make(map[string]int)
for _, content := range replies {
memberCount[content.Member.Username] += 1
}
// 仅回复一次的会被收集到 members 里,不过可能有误伤,输出了多次回复的用户
var members []string
for k, v := range memberCount {
if v > 1 {
fmt.Printf("用户 %v 回复了 %v\n", k, v)
} else {
members = append(members, k)
}
}
// hc 代表幸运用户数量,赋值为三代表抽取三名
var hc = 3
rand.Seed(time.Now().UnixNano())
fmt.Printf("====== %v名幸运用户是 ======\n", hc)
for i := 0; i < hc; i++ {
fmt.Println(members[rand.Int()%len(members)]) // 这样单行这么复杂,是不是不太Golang?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.