我有一个名词数据库(例如“房子”、“感叹号”、“苹果”),我需要在我的应用程序中输出和描述这些名词。如果不使用“a”或“an”——“a house is BIG”、“a exclamation point is SMALL”等,很难用听起来自然的句子来描述一个项目。
我可以在 PHP 中使用任何函数、库或 hack 来确定用 A 还是 AN 来描述任何给定名词更合适?
最佳答案
我的 C# 项目需要这个,所以这是 Python code 的 C# 端口上文提到的。确保在源文件中包含 using System.Text.RegularExpressions;
。
private string GetIndefiniteArticle(string noun_phrase)
{
string word = null;
var m = Regex.Match(noun_phrase, @"\w+");
if (m.Success)
word = m.Groups[0].Value;
else
return "an";
var wordi = word.ToLower();
foreach (string anword in new string[] { "euler", "heir", "honest", "hono" })
if (wordi.StartsWith(anword))
return "an";
if (wordi.StartsWith("hour") && !wordi.StartsWith("houri"))
return "an";
var char_list = new char[] { 'a', 'e', 'd', 'h', 'i', 'l', 'm', 'n', 'o', 'r', 's', 'x' };
if (wordi.Length == 1)
{
if (wordi.IndexOfAny(char_list) == 0)
return "an";
else
return "a";
}
if (Regex.Match(word, "(?!FJO|[HLMNS]Y.|RY[EO]|SQU|(F[LR]?|[HL]|MN?|N|RH?|S[CHKLMNPTVW]?|X(YL)?)[AEIOU])[FHLMNRSX][A-Z]").Success)
return "an";
foreach (string regex in new string[] { "^e[uw]", "^onc?e\b", "^uni([^nmd]|mo)", "^u[bcfhjkqrst][aeiou]" })
{
if (Regex.IsMatch(wordi, regex))
return "a";
}
if (Regex.IsMatch(word, "^U[NK][AIEO]"))
return "a";
else if (word == word.ToUpper())
{
if (wordi.IndexOfAny(char_list) == 0)
return "an";
else
return "a";
}
if (wordi.IndexOfAny(new char[] { 'a', 'e', 'i', 'o', 'u' }) == 0)
return "an";
if (Regex.IsMatch(wordi, "^y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt)"))
return "an";
return "a";
}
关于php - 以编程方式确定是用 "a"还是 "an"来描述对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4558437/