2019 GPLT L1-8 估值一亿的AI核心代码
以上图片来自新浪微博。
本题要求你实现一个稍微更值钱一点的 AI 英文问答程序,规则是:
- 无论用户说什么,首先把对方说的话在一行中原样打印出来;
- 消除原文中多余空格:把相邻单词间的多个空格换成 1 个空格,把行首尾的空格全部删掉,把标点符号前面的空格删掉;
- 把原文中所有大写英文字母变成小写,除了
I
; - 把原文中所有独立的
can you
、could you
对应地换成I can
、I could
—— 这里“独立”是指被空格或标点符号分隔开的单词; - 把原文中所有独立的
I
和me
换成you
; - 把原文中所有的问号
?
换成惊叹号!
; - 在一行中输出替换后的句子作为 AI 的回答。
输入格式:
输入首先在第一行给出不超过 10 的正整数 N,随后 N 行,每行给出一句不超过 1000 个字符的、以回车结尾的用户的对话,对话为非空字符串,仅包括字母、数字、空格、可见的半角标点符号。
输出格式:
按题面要求输出,每个 AI 的回答前要加上 AI:
和一个空格。
输入样例:
6
Hello ?
Good to chat with you
can you speak Chinese?
Really?
Could you show me 5
What Is this prime? I,don 't know
输出样例:
Hello ? AI: hello! Good to chat with you AI: good to chat with you can you speak Chinese? AI: I can speak chinese! Really? AI: really! Could you show me 5 AI: I could show you 5 What Is this prime? I,don 't know AI: what Is this prime! you,don't know
(因为懒,就不总结题意了,就这题把我卡了20多分钟一分没拿)
思路就是
首先进行字符串的预处理
将原串中的'?'变为'!'
将标点单独分离出来,以便后面控制格式
将大写字母变成小写
然后将字符串分段
这里我们使用stringstream来分解字符串(不懂的小伙伴可以先百度)
我使用了vector<stirng>来保存串,当然你也可以使用string数组
然后分情况讨论输出就可以了
具体的解释我都写在注释里了
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 vector<string> q; 6 7 int main() 8 { 9 int n; 10 string s; 11 cin >> n; 12 getchar(); //getline()之前吃回车 13 while(n--) 14 { 15 q.clear(); //别忘了清空 16 getline(cin,s); 17 cout << s << endl << "AI:"; 18 for(int i = 0; i < s.size(); i++) //预处理 19 { 20 if(isalpha(s[i])) 21 { 22 if(s[i] != 'I') s[i] = tolower(s[i]); 23 } 24 if(!isalnum(s[i])) 25 { 26 s.insert(i," "); 27 i++; // 这个地方千万不能忘 28 } 29 if(s[i] == '?') s[i] = '!'; 30 } 31 stringstream ss(s); //清理空格 32 while(ss >> s) 33 { 34 q.push_back(s); 35 } 36 if(!isalnum(q[0][0])) cout << " "; 37 for(int i = 0; i < q.size(); i++) 38 { 39 if(!isalnum(q[i][0])) 40 { 41 cout << q[i]; 42 } 43 else if(q[i] == "can" && i+1 < q.size() && q[i+1] == "you") 44 { 45 cout << " I can"; 46 i++; //这里也千万别忘了 47 } 48 else if(q[i] == "could" && i+1 < q.size() && q[i+1] == "you") 49 { 50 cout << " I could"; 51 i++;//这里也千万别忘了 52 } 53 else if(q[i] == "I" || q[i] == "me") 54 { 55 cout << " you"; 56 } 57 else cout << " " << q[i]; 58 } 59 cout << endl; 60 } 61 return 0; 62 }