示例:聊天机器人
结合咱们之前的学习,本节带领大家来编写一个聊天机器人的雏形,下面的代码中展示了一个简单的聊天程序。
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!
所有教程
- C语言入门
- C语言编译器
- C语言项目案例
- 数据结构
- C++
- STL
- C++11
- socket
- GCC
- GDB
- Makefile
- OpenCV
- Qt教程
- Unity 3D
- UE4
- 游戏引擎
- Python
- Python并发编程
- TensorFlow
- Django
- NumPy
- Linux
- Shell
- Java教程
- 设计模式
- Java Swing
- Servlet
- JSP教程
- Struts2
- Maven
- Spring
- Spring MVC
- Spring Boot
- Spring Cloud
- Hibernate
- Mybatis
- MySQL教程
- MySQL函数
- NoSQL
- Redis
- MongoDB
- HBase
- Go语言
- C#
- MATLAB
- JavaScript
- Bootstrap
- HTML
- CSS教程
- PHP
- 汇编语言
- TCP/IP
- vi命令
- Android教程
- 区块链
- Docker
- 大数据
- 云计算