估值一億的AI核心代碼 (20分)
以上圖片來自新浪微博。
本題要求你實現一個稍微更值錢一點的 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
比賽時被這道題給整自閉了,浪費太長時間也沒通過。
通過其他博客大佬讓我瞭解到了c++中regex這個好東西,不到40行就可以AC。再也不用那麼麻煩的去處理字符串了。
regex是用來處理正則表達式,裏面有個函數regex_replace(string s, regex re, string new_string)可以將s中滿足正則表達式re的所有位置替換成new_string。
AC代碼:
#include<iostream>
#include<regex>
using namespace std;
int main(void){
int n;
cin>>n;
getchar();
while(n--){
string s;
getline(cin,s);
cout<<s<<endl;
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"( ')"), "'");
for (auto &c : s) {
if(c != 'I') c = tolower(c);
}
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"(\bI\b)"), "you");
s = regex_replace(s, regex(R"(\bme\b)"), "you");
s = regex_replace(s, regex(R"(\?)"), "!");
s = regex_replace(s, regex(R"(\b_I\b)"), "I");
cout << "AI: " << s << endl;
}
return 0;
}
學無止境呀!