示例:聊天机器人

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

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

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...