![](/img/trans.png)
[英]Count the number of unique words and occurrence of each word from txt file
[英]Get x number of unique words on each side of a word in a string?
我正在嘗試在C#字符串中的單詞的每一側獲取x個唯一單詞。 例如方法
GetUniqueWords("she sells seashells, by the seashore. the shells she sells, are surely seashells.", "seashore", 3)
(第一個參數是句子字符串。第二個參數是用於獲取其兩側單詞的單詞。第三個參數是要檢查的單詞數)
將返回帶有值的字符串列表:
貝殼
通過
該
炮彈
她
提前致謝。
不漂亮,但是為您的示例工作:-)
private static IEnumerable<string> GetUniqueWords(string phrase, string word, int amount)
{
//Clean up the string and get the words
string[] words = Regex.Split(phrase.Replace(".","").Replace(",",""),@"\s+");
//Find the first occurrence of the desired word (spec allows)
int index = Array.IndexOf(words,word);
//We don't wrap around the edges if the word is the first,
//we won't look before if last, we won't look after, again, spec allows
int min = (index - amount < 0) ? 0 : index - amount;
int max = (index + amount > words.Count() - 1) ? words.Count() - 1 : index + amount;
//Add all the words to a list except the supplied one
List<string> rv = new List<string>();
for (int i = min; i <= max; i++)
{
if (i == index) continue;
rv.Add(words[i]);
}
//Unique-ify the resulting list
return rv.Distinct();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.