示例:聊天机器人

示例:聊天机器人,第1张

概述结合咱们之前的学习,本节将带领大家来编写一个聊天机器人的雏形。下面的代码中展示了一个很傻的聊天程序。 package mainimport ( bufio fmt os strings)func main() { // 准备从标准输入读取数据 结合咱们之前的学习,本节带领大家来编写一个聊天机器人的雏形,下面的代码中展示了一个简单的聊天程序。
package mainimport (    "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!

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

以上是内存溢出为你收集整理的示例:聊天机器人全部内容,希望文章能够帮你解决示例:聊天机器人所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1271134.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存