• 示例:聊天机器人

    结合咱们之前的学习,本节带领大家来编写一个聊天机器人的雏形,下面的代码中展示了一个简单的聊天程序。

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "strings"
    )
    
    func main() {
        // 准备从标准输入读取数据。
        inputReader := bufio.NewReader(os.Stdin)
        fmt.Println("Please input your name:")
        // 读取数据直到碰到 \n 为止。
        input, err := inputReader.ReadString('\n')
        if err != nil {
            fmt.Printf("An error occurred: %s\n", err)
            // 异常退出。
            os.Exit(1)
        } else {
            // 用切片操作删除最后的 \n 。
            name := input[:len(input)-2]
            fmt.Printf("Hello, %s! What can I do for you?\n", name)
        }
        for {
            input, err = inputReader.ReadString('\n')
            if err != nil {
                fmt.Printf("An error occurred: %s\n", err)
                continue
            }
            input = input[:len(input)-2]
            // 全部转换为小写。
            input = strings.ToLower(input)
            switch input {
            case "":
                continue
            case "nothing", "bye":
                fmt.Println("Bye!")
                // 正常退出。
                os.Exit(0)
            default:
                fmt.Println("Sorry, I didn't catch you.")
            }
        }
    }

    这个聊天程序在问候用户之后会不断地询问“是否可以帮忙”,但是实际上它什么忙也帮不上,因为它现在什么也听不懂,除了 nothing 和 bye,一看到这两个词,它就会与用户“道别”,停止运行,现在试运行一下这个命令源码文件:

    D:\code>go run test.go
    Please input your name:
    ->Robert
    Hello, Robert! What can I do for you?
    ->A piece of cake, please.
    Sorry, I didn't catch you.
    ->Bye
    Bye!

    注意,其中的“->”符号之后的内容是我们输入的。

更多...

加载中...