我正在尝试检测 player.LastChat 的书面文本是什么语言,但我遇到了一些困难。
这是我的代码:
String[] words = player.LastChat.Trim().Split(new Char[]{' ','\t',',','.',':','!','?',';','(',')',']','[','"'});
StringBuilder edited = new StringBuilder();
// Remove exception list words from line
foreach (String w in words) {
if (plugin.isInList(w, "good_words")) {
continue;
}
edited.Append(w);
edited.Append(" ");
}
// URL Encode edited string
String UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
StringBuilder Result = new StringBuilder();
String Input = edited.ToString();
for (int x = 0; x < Input.Length; ++x)
{
if (UnreservedChars.IndexOf(Input[x]) != -1)
Result.Append(Input[x]);
else
Result.Append("%").Append(String.Format("{0:X2}", (int)Input[x]));
}
String key = "API KEY";
// Test for badness
bool jsonresult = false;
try {
WebClient client = new WebClient();
String json = client.DownloadString("https://www.googleapis.com/language/translate/v2/detect?key=" + key + "&q=" + Result.ToString());
jsonresult = json.Contains("en");
} catch (Exception e) {
plugin.ConsoleWrite("Language check failed! Error: " + e);
}
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult; // for Actions
所以,我想要实现的是,如果它是“en”(英语)以外的任何其他语言,则返回 true,但无论如何它都会返回 true。
google 的回复是这样的:
{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.03396887
}
]
]
}
}
非常感谢任何帮助,我不知道如何编码,这段代码是从另一个脚本借来的。
问候。
请您参考如下方法:
要使方法按描述工作,您应该更改:
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult;
到:
plugin.ConsoleWrite("Language: " + jsonresult);
return !jsonresult;
还有这条线
jsonresult = json.Contains("en");
正在检查 json 文本中是否出现任何 "en"(并在您的 json 中的 "confidence" 中找到)。你应该做的是使用 json.net(或其他库)解析 Json,或者只是这样做(但这是一个丑陋的 hack):
jsonresult = json.Contains("\"language\": \"en\",");
