2016-12-03 21 views
-5

Ich brauche Hilfe. Ich muss Wörter finden, die in text1, aber nicht in text2 sind, zählen auch, wie oft sie auftreten.C# verschiedene Wörter in zwei Texten finden

Beispiel:

Text1 (hallo, Welt Apfel, Ananas, Kohl, Apfel)

Text2 (hallo, Welt, Ananas)

Ergebnis:

Apfel 2;

Kohl1;

Auch wäre es genial, es zu tun, ohne Liste

+0

Warum „Welt Apfel“ zum Beitrag Zählung von "Apfel"? –

+0

Ich meine, das ist ein Text wie (Apfel mag Ananas, Hallo Welt, wie geht es dir?) Also muss ich jedes andere Wort und seinen Zähler finden. –

Antwort

1
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(); 

Dies kehrt

Word = apple, Count = 2 
Word = cabbage, Count = 1 

Natürlich gibt es für einige Leistungsverbesserungen Zimmer, aber es wird sie für Klarheit auslassen ...

2

Sie zwei Array verwenden können und dann Group By verwenden Sie Ihr Ziel auf diese Weise erreichen können:

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()); 

Edit:

Es sieht so aus, als ob Sie die Lösung auf eine etwas andere Art und Weise haben wollen, also zeige ich das auch unten:

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()); 
+0

negativer Wähler? Warum negative Stimme? –

Verwandte Themen