Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "io/ioutil"
- "regexp"
- "time"
- )
- // Message Define a message structure
- type Message struct {
- Name string
- Message string
- Time time.Time
- }
- // Messages Hold a slice for all the messages a user was posting at the log file
- type Messages []Message
- // Chats hold a map for all chats at the log based on users
- type Chats map[string]Messages
- func lineToMessage(line string) (Message, error) {
- re := regexp.MustCompile(`^\[([^\]]+)\] ([^:]+): (.*?)$`)
- result := re.FindStringSubmatch(line)
- if len(result) != 4 {
- return Message{}, fmt.Errorf("Invalid line format")
- }
- tm, err := time.Parse("2006-01-02 03:04:05 MST", result[1])
- if err != nil {
- return Message{}, err
- }
- msg := Message{
- Time: tm,
- Name: result[2],
- Message: result[3],
- }
- return msg, nil
- }
- func mapChats(lines []string) (chats Chats, err error) {
- chats = make(Chats)
- for _, line := range lines {
- msg, err := lineToMessage(line)
- if err != nil {
- return chats, err
- }
- chats[msg.Name] = append(chats[msg.Name], msg)
- }
- return
- }
- func parseFile(path string) (chats Chats, err error) {
- buff, err := ioutil.ReadFile(path)
- if err != nil {
- return chats, err
- }
- var lines []string
- line := ""
- for _, ch := range buff {
- if ch == '\n' {
- lines = append(lines, line)
- line = ""
- continue
- }
- line = line + string(ch)
- }
- chats, err = mapChats(lines)
- return chats, err
- }
- func main() {
- chats, err := parseFile("chat.log")
- if err != nil {
- panic(err)
- }
- for key, value := range chats {
- fmt.Printf("User: %s have #%d lines\n", key, len(value))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement