以上圖片來自新浪微博。
本題要求你實現一個稍微更值錢一點的 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
正則表達式
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
int N;
string s;
cin >> N;
getchar();
while (N--) {
getline(cin, s);
cout << s << endl << "AI: ";
for (int i = 0; i < s.size(); ++i)
if (s[i] != 'I')
s[i] = tolower(s[i]);
s = regex_replace(s, regex(R"(\s+)"), " ");
if (s.front() == ' ') s.erase(s.begin());
if (s.back() == ' ') s.pop_back();
s = regex_replace(s, regex(R"( ?\?| !)"), "!");
s = regex_replace(s, regex(R"( ,)"), ",");
s = regex_replace(s, regex(R"( ')"), "'");
s = regex_replace(s, regex(R"( \.)"), ".");
s = regex_replace(s, regex(R"(\bI\b|\bme\b)"), "y_u"); //測試點1:考慮到can I的情況
s = regex_replace(s, regex(R"(\bcan you\b)"), "I can");
s = regex_replace(s, regex(R"(\bcould you\b)"), "I could");
s = regex_replace(s, regex(R"(y_u)"), "you");
cout << s << endl;
}
}
上面那個是自己現學了正則表達式語法寫出來的,下面的是學長寫好的,也get到了一個新的輸入輸出類
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int N;
string s;
cin >> N;
getchar();
while (N--) {
getline(cin, s);
cout << s << endl << "AI:";
for (int i = 0; i < s.size(); ++i) {
if (isalnum(s[i])) {
if (s[i] != 'I')
s[i] = tolower(s[i]);
}
else {
s.insert(i, " ");
i++;
}
if (s[i] == '?')
s[i] = '!';
}
stringstream str(s);
string a[1000];
int cnt = 0;
while (str >> s)
a[cnt++] = s;
if (!isalnum(a[0][0]))
cout << " ";
for (int i = 0; i < cnt; ++i) {
if (!isalnum(a[i][0])) {
cout << a[i];
}
else if (a[i] == "can" && a[i + 1] == "you") {
cout << " I can";
i++;
}
else if (a[i] == "could" && a[i + 1] == "you") {
cout << " I could";
i++;
}
else if (a[i] == "I" || a[i] == "me")
cout << " you";
else
cout << " " << a[i];
}
cout << endl;
}
return 0;
}