聊天机器人(Magpie Chatbot Lab)活动3:更好的关键字检测
在上一个活动中,你已经发现在字符串中单纯按字母查找并不总会达到你想要的效果。例如,“Let’s play catch!”里也有“cat”这个词,但这句话和动物没有任何关系。在本活动中,你将跟踪研究一个对字符串进行全字匹配的method。其将检查欲匹配目标前后的子串,确保找到的是正确的关键字。
本活动中你会使用一些更复杂的String method。Class String有很多有用的method,并不包括在AP计算机Java子集中。但在某些情况下,它们会很管用,因此在这里你会学习如何使用API来探索Java提供的全部method。
准备
确保你有:
Class Magpie的APIClass String的APIStringExplorer代码Magpie代码MagpieRunner代码- 带有Java开发工具的电脑
探索:API
利用Java语言进行编程的很大优势之一是它已经有数以万计的现成库和class可供直接使用。
运行StringExplorer程序。这一程序有代码来展示indexOf和toLowerCase的使用。
打开String的API。向下滚动至Method一览这节,找到indexOf(String str) method。点击链接并阅读indexOf method的说明。如果子串未出现,indexOf会返回什么值?
将以下几行代码加入到StringExplorer中,自己看看indexOf是如何运作的。
int notFoundPsn = sample.indexOf("slow");
System.out.println("sample.indexOf(\"slow\") = " + notFoundPsn);
接下来阅读indexOf(String str, int fromIndex)的说明。在StringExplorer中加入代码,查看其与一个参数的版本有什么区别。
本实验活动将使用一系列不同的String method。在看到自己所不熟悉的method时请参考API。
探索:理解新method
这个版本的class Magpie有一个名为findKeyword的method用来检测关键字。这个method只会找到关键字的精确匹配,而不是作为更长的某个词的一部分。按照老师的指示运行它。
private int findKeyword(String statement, String goal, int startPos)
{
String phrase = statement.trim().toLowerCase();
goal = goal.toLowerCase();
int psn = phrase.indexOf(goal, startPos);
while (psn >= 0) {
String before = " ", after = " ";
if (psn > 0) {
before = phrase.substring(psn - 1, psn);
}
if (psn + goal.length() < phrase.length()) {
after = phrase.substring(psn + goal.length(), psn + goal.length() + 1);
}
/* determine the values of psn, before, and after at this point in the method. */
if (((before.compareTo("a") < 0) || (before.compareTo("z") > 0))
&&
((after.compareTo("a") < 0) || (after.compareTo("z") > 0)))
{
return psn;
}
psn = phrase.indexOf(goal, psn + 1);
}
return -1;
}
从头到尾阅读findKeyword method。为了确保你的充分理解,你应该尝试跟踪以下调用的执行。
findKeyword("She's my sister", "sister", 0);
findKeyword("Brother Tom is helpful", "brother", 0);
findKeyword("I can't catch wild cats.", "cat", 0);
findKeyword("I know nothing about snow plows.", "no", 0);
写出变量psn,before和after在程序执行到注释处的值。
例子:findKeyword("yesterday is today's day before.", "day", 0)
| 循环 | psn |
before |
after |
| 1 | 6 | “r” | ” “ |
| 2 | 15 | “o” | “‘” |
| 3 | 21 | ” “ | ” “ |
使用同样的表格进行调用跟踪。
| 循环 | psn |
before |
after |
练习
重复在活动2中进行的改动,使用新method检测关键字。
问题
- 单个关键字固然有趣,但更好的聊天机器人查找一组关键字。考虑诸如“I like cats”,“I like math class”和“I like Spain”,它们都有“I like something”的形式。对此,回复可以是“What do you like about something?”下一个活动将围绕这个问题,你也需要编写你自己的关键字组,所以可以现在开始留意自己日常对话中出现的常见词组。
1 条评论
AP计算机科学实验:聊天机器人(Magpie Chatbot Lab) – AP Computer Science · 2018年4月28日 上午10:39
[…] 活动3:更好的关键字检测 […]