我想制作Twitter Sentiment Analysis Windows Phone应用程序。
该应用程序的工作原理是根据用户输入的查询字词检索所有相关推文。例如,如果我在输入搜索框中输入“Windows Phone”,结果将显示包含“windows phone”条款的所有推文。
这是代码(我从Arik Poznanski's Blog获得)
/// <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;
}
但是,不仅要检索一条推文,还会有很多推文,所以主要问题是,在我检索完所有推文并向API请求结果后,我收到此错误“WebClient不会支持并发I / O操作“
有谁知道如何解决这个问题?
任何帮助将不胜感激
答案 0 :(得分:1)
您必须一次同步执行UploadStringAsync。 (即在UploadStringCompleted处理程序中链式执行下一个UploadStringAsync。
或者,为每个UploadStringAsync创建一个新的WebClient。