我正在建立一个madlib。我一直在研究正则表达式作为一种方法来做到这一点,但任何建议都可以提供帮助。此代码示例仅用于第一句。也许在没有正则表达式的情况下,这样做更简单。也许某些东西可以抓住句子中的单词并忽略空格,或者使用空格和标点来最终将单词解析为对象。
class Program
{
string userWord1;
string userWord2;
static void Main()
{
List<string> words = new List<string>();
List<string> words2 = new List<string>();
string userWord1;
string[] a = SplitWords("Today I went to the zoo."
+ " I saw a " + adjective1 + noun1 + "jumping up and down in it's tree."
+ " He " + verb1 + adverb1 + " through the large tunnel that led to led to it's " + adjective2 + noun2
+ " I got some peanuts and passed them through the cage to a gigantic gray " + noun3 + " towering above my head."
+ " Feeding that animal made me hungry."
+ " I went to get a " + adjective3 + " of ice-cream.
+ " It filled my stomach."
+ " Afterwards I had to " + verb2 + adverb2 + " to catch our bus"
+ " When I got home I " + verb3 + " my mom for a" + adjective3 + " day at the zoo.");
string[] b = SplitWords2("I saw a adjective noun jumping up and down in it's tree.");
foreach (string s in a)
{
Console.Write(" ");
Console.Write(s);
words.Add(s);
}
string sentence = string.Join(",", words.ToArray());
Console.WriteLine(sentence);
Regex r = new Regex(@"\went\b"); //@"\adjective\b")
sentence = r.Replace(sentence, "@@");
Console.WriteLine(sentence);
foreach (string t in b)
{
Console.Write(" ");
Console.Write(s);
words2.Add(t);
}
string sentence2 = string.Join(",", words2.ToArray());
Console.WriteLine(sentence2);
Regex br = new Regex(@"\adjective\b"); //@"\adjective\b")
sentence2 = br.Replace(sentence2, "@@");
Console.WriteLine(sentence2);
}
static string[] SplitWords(string s)
{
return Regex.Split(s, @"\Ww+[.?:;!_]");
@ special verbatim string syntax
\W + one or more non - word characters together
}
}