Microsoft.TranslatorContainer.Detect C# (CSharp) Method

Detect() public method

public Detect ( String Text ) : DataServiceQuery
Text String the text whose language is to be identified Sample Values : hello
return DataServiceQuery
        public DataServiceQuery<DetectedLanguage> Detect(String Text) {
            if ((Text == null)) {
                throw new System.ArgumentNullException("Text", "Text value cannot be null");
            }
            DataServiceQuery<DetectedLanguage> query;
            query = base.CreateQuery<DetectedLanguage>("Detect");
            if ((Text != null)) {
                query = query.AddQueryOption("Text", string.Concat("\'", System.Uri.EscapeDataString(Text), "\'"));
            }
            return query;
        }
    }

Usage Example

Exemplo n.º 1
0
        /// <summary>
        /// Uses the TranslatorContainer to identify the Language in which inputString was written
        /// </summary>
        /// <param name="tc">The TranslatorContainer to use</param>
        /// <param name="inputString">The string to identify</param>
        /// <returns>The Language Code for a language that this string could represent,
        /// or null if one is not found.</returns>
        private static DetectedLanguage DetectSourceLanguage(TranslatorContainer tc, string inputString)
        {
            // calling Detect gives us a DataServiceQuery which we can use to call the service
            var translateQuery = tc.Detect(inputString);

            // since this is a console application, we do not want to do an asynchronous
            // call to the service. Otherwise, the program thread would likely terminate
            // before the result came back, causing our app to appear broken.
            var detectedLanguages = translateQuery.Execute().ToList();

            // since the result of the query is a list, there might be multiple
            // detected languages. In practice, however, I have only seen one.
            // Some input strings, 'hi' for example, are obviously valid in
            // English but produce other results, suggesting that the service
            // only returns the first result.
            if (detectedLanguages.Count() > 1)
            {
                Console.WriteLine("Possible source languages:");

                foreach (var language in detectedLanguages)
                {
                    Console.WriteLine("\t" + language.Code);
                }

                Console.WriteLine();
            }

            // only continue if the Microsoft Translator identified the source language
            // if there are multiple, let's go with the first.
            if (detectedLanguages.Count() > 0)
            {
                return(detectedLanguages.First());
            }
            else
            {
                return(null);
            }
        }