我需要幫助。 我需要找到文本1中的文本,但不是文本2中的文字,還要計算它們出現的次數。c#在兩個文本中找到不同的單詞
實施例:
文本1(你好,世界蘋果,菠蘿,大白菜,蘋果)
文本2(你好,世界,菠蘿)
結果:
蘋果2;
cabbage1;
而且這將是真棒做纔不至於列表
我需要幫助。 我需要找到文本1中的文本,但不是文本2中的文字,還要計算它們出現的次數。c#在兩個文本中找到不同的單詞
實施例:
文本1(你好,世界蘋果,菠蘿,大白菜,蘋果)
文本2(你好,世界,菠蘿)
結果:
蘋果2;
cabbage1;
而且這將是真棒做纔不至於列表
string text1 = "hello, world apple,pineapple,cabbage,apple";
string text2 = "hello, world,pineapple";
string pattern = @"\p{L}+";
var list1 = Regex.Matches(text1, pattern).Cast<Match>().Select(x => x.Value);
var list2 = Regex.Matches(text2, pattern).Cast<Match>().Select(x => x.Value);
var result = list1.Where(x => !list2.Contains(x))
.GroupBy(x => x)
.Select(x =>new
{
Word = x.Key,
Count= x.Count()
})
.ToList();
這將返回
Word = apple, Count = 2
Word = cabbage, Count = 1
當然有餘地的一些性能改進,但它會離開他們出去清晰...
您可以使用兩個數組,然後使用Group By
就可以實現這樣的目標:
string[] text1 = new []{"hello", "world", "apple", "pineapple", "cabbage", "apple"};
string[] text2 = new []{"apple", "pineapple", "cabbage", "apple"};
string[] combinedText = text1.Concat(text2).ToArray();
var groups = combinedText.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
編輯:
它看起來像你想解決方案略有不同的方式,所以我也顯示如下:
string[] text1 = new []{"hello", "world", "apple", "pineapple", "cabbage", "apple"};
string[] text2 = new []{"apple", "pineapple", "cabbage", "apple"};
var text1Groups = text1.GroupBy(v => v);
var text2Groups = text2.GroupBy(v => v);
foreach(var group in text1Groups)
Console.WriteLine(group.Key.ToString() + group.Count().ToString());
foreach(var group in text2Groups)
Console.WriteLine(group.Key.ToString() + group.Count().ToString());
負面選民?爲什麼反對投票? –
爲什麼「蘋果世界」貢獻了數「蘋果」? –
我的意思是說,這是一個文字(蘋果喜歡菠蘿,你好,世界,你好嗎?)所以我需要找到每個不同的單詞和它的櫃檯。 –