0

我想做 Twitter 情绪分析 Windows Phone 应用程序。

该应用程序通过根据用户输入的查询词检索所有相关推文来工作。例如,如果我在输入搜索框中输入“Windows Phone”,结果将显示所有包含“Windows Phone”字词的推文。

这是代码(我从Arik Poznanski 的博客中获得)

    /// <summary>
    /// Searches the specified search text.
    /// </summary>
    /// <param name="searchText">The search text.</param>
    /// <param name="onSearchCompleted">The on search completed.</param>
    /// <param name="onError">The on error.</param>
    public static void Search(string searchText, Action<IEnumerable<Twit>> onSearchCompleted = null, Action<Exception> onError = null, Action onFinally = null)
    {
        WebClient webClient = new WebClient();

        // register on download complete event
        webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                // report error
                if (e.Error != null)
                {
                    if (onError != null)
                    {
                        onError(e.Error);
                    }
                    return;
                }

                // convert json result to model
                Stream stream = e.Result;
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(TwitterResults));
                TwitterResults twitterResults = (TwitterResults)dataContractJsonSerializer.ReadObject(stream);

                App thisApp = Application.Current as App;
                thisApp.klasifikasi = new Klasifikasi();

                foreach (Twit Tweet in twitterResults.results)
                {
                    try
                    {
                        thisApp.klasifikasi.UploadData(Tweet); //requesting 
                        break;
                    }
                    finally
                    {
                        // notify finally callback
                        if (onFinally != null)
                        {
                            onFinally();
                        }
                    }
                }
                //thisApp.klasifikasi.UploadDatas(twitterResults.results);
                //thisApp.PositiveTweetModel = new PositiveTweetModel("Positive", twitterResults.results);

                // notify completed callback
                if (onSearchCompleted != null)
                {
                    onSearchCompleted(twitterResults.results);

                   /// Divide the list here

                }
            }
            finally
            {
                // notify finally callback
                if (onFinally != null)
                {
                    onFinally();
                }
            }
        };

        string encodedSearchText = HttpUtility.UrlEncode(searchText);
        webClient.OpenReadAsync(new Uri(string.Format(TwitterSearchQuery, encodedSearchText)));
    }

并调用该方法

           TwitterService.Search(
            text,
           (items) => { PositiveList.ItemsSource = items; },
           (exception) => { MessageBox.Show(exception.Message); },
           null
           );

将 POST 数据上传到 API

    public void UploadData(Twit tweetPerSend)
    {
        if (NetworkInterface.GetIsNetworkAvailable())
        {
            chatterbox.Headers[HttpRequestHeader.ContentType] = "application/x-www-                       form-urlencoded";
            chatterbox.Headers["X-Mashape-Authorization"] = "MXBxYmptdjhlbzVnanJnYndicXNpN2NwdWlvMWE1OjA0YTljMWJjMDg4MzVkYWY2YmIzMzczZWFkNDlmYWRkNDYzNGU5NmI=";

            var Uri = new Uri("https://chatterboxco-sentiment-analysis-for-social-media---nokia.p.mashape.com/sentiment/current/classify_text/");

            StringBuilder postData = new StringBuilder();
            postData.AppendFormat("{0}={1}", "lang", HttpUtility.UrlEncode("en"));
            postData.AppendFormat("&{0}={1}", "text", HttpUtility.UrlEncode(tweetPerSend.DecodedText));
            postData.AppendFormat("&{0}={1}", "exclude", HttpUtility.UrlEncode("is")); // disesuaikan 
            postData.AppendFormat("&{0}={1}", "detectlang", HttpUtility.UrlEncode("0"));
            chatterbox.UploadStringAsync(Uri, "POST", postData.ToString());
            chatterbox.UploadStringCompleted += new UploadStringCompletedEventHandler(chatterbox_UploadStringCompleted);

        }
    }


    void chatterbox_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        var chatterbox = sender as WebClient;
        chatterbox.UploadStringCompleted -= chatterbox_UploadStringCompleted;
        string response = string.Empty;
        if (!e.Cancelled)
        {
            response = HttpUtility.UrlDecode(e.Result);
            nilaiKlasifikasi = ParsingHasil(response);
            MessageBox.Show(nilaiKlasifikasi.ToString()); //just testing
            //textBlock1.Text = response;
        }
    }

    private double ParsingHasil(String response)
    {

        var result = Regex.Match(@response, @"(?<=""value"": )(-?\d+(\.\d+)?)(?=,|$)");
        Debug.WriteLine(result);
        double hasil = Convert.ToDouble(result.ToString());
        //return Convert.ToInt32(result);
        return hasil;

    }

但是,不仅要检索 1 条推文,还会有很多推文,所以主要问题是,在我检索所有推文并向 API 请求结果后,我收到此错误“WebClient does not support concurrent I /O 操作"

有谁知道如何解决这个问题?

任何帮助,将不胜感激

4

1 回答 1

1

您必须一次同步执行一个 UploadStringAsync。(即在 UploadStringCompleted 处理程序中链式执行下一个 UploadStringAsync。

或者,为每个 UploadStringAsync 创建一个新的 WebClient。

于 2012-12-16T06:14:24.563 回答