這是我的代碼:
string StringFromTheInput = TextBox1.Text;
string source = StringFromTheInput.ToString();
var frequencies = new Dictionary<string, int>();
frequencies.Add("item", 0);
string highestWord = null;
var message = string.Join(" ", source);
var splichar = new char[] { ' ', '.' };
var single = message.Split(splichar);
int highestFreq = 0;
foreach (var item in single)
{
if (item.Length > 4)
{
int freq;
frequencies.TryGetValue(item, out freq);
freq = 1;
if (freq> highestFreq)
{
highestFreq = freq;
highestWord = item.Trim();
}
frequencies[item] = freq;
Label1.Text = highestWord.ToString();
}
}
這成功地讓我從文本中獲得了最常見的單詞,但我試圖增加highestFreq= freq 1 以獲得第二個最常見的單詞,但它不起作用!
uj5u.com熱心網友回復:
你可以使用 Linq 還是這是作業?
using System;
using System.Linq;
string StringFromTheInput = "Her life in the confines of the house became her new normal. He wondered if she would appreciate his toenail collection. My secretary is the only person who truly understands my stamp-collecting obsession. This is the last random sentence I will be writing and I am going to stop mid-sent. She tilted her head back and let whip cream stream into her mouth while taking a bath.";
string[] words = StringFromTheInput.Split(" ");
var setsByFrequency = words
.Where(x => x.Length > 4) // For words with more than 4 characters
.GroupBy(x => x.ToLower()) // ToLower so 'House' and 'house' both gets placed into the same group
.Select(g => new { Freq = g.Count(), Word = g.Key})
.OrderByDescending(g => g.Freq)
.ToList();
var mostFrequent = setsByFrequency[0];
var secondMostFrequent = setsByFrequency[1];
Console.WriteLine(mostFrequent);
Console.WriteLine(secondMostFrequent);
uj5u.com熱心網友回復:
您可以按字典的值排序,然后取第一個,第二個...找到的元素。
int indexYouNeed =2;
int indexRead=1;
string textFound="";
foreach (KeyValuePair<string,int> entry in frequencies.Where(x=>x.Key.Length>4).OrderBy(x=>x.Value))
{
if(indexRead==indexYouNeed)
{
textFound=entry.Key;
break;
}
indexRead ;
}
uj5u.com熱心網友回復:
我會做這樣的事情(簡單易懂)首先,用你的單詞和頻率加載字典(只有超過 4 個字符的單詞,因為我在你的問題中看到了),在這種情況下,字典必須忽略大小寫. 其次,訂購字典并取第二個(請檢查它是否為空,或者在嘗試訪問之前是否只有1個元素):
string StringFromTheInput = "";
var wordsFreq = new Dictionary<string,int>(StringComparer.OrdinalIgnoreCase);
foreach(var s in StringFromTheInput.Split(' ')){
if(s.Length <=4) continue;
if(wordsFreq.ContainsKey(s)){
wordsFreq[s] ;
}else{
wordsFreq.Add(s,1);
}
}
if(!wordsFreq.Any()) return;
var secondFreqWord = wordsFreq.OrderByDescending(x => x.Value).ToList()[1];
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531099.html
標籤:C#网asp.net-mvc-3asp.net-web-apinlp
下一篇:如何在我的代碼DateTimeStartTime=StartDateValue StartTimeNames[0]中實作這一點?